repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
30
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-06-13 10:24:29
hints_text
stringlengths
0
234k
base_commit
stringlengths
40
40
test_instructions
stringlengths
0
232k
filenames
listlengths
0
300
juspay/hyperswitch
juspay__hyperswitch-4127
Bug: remove mandates from nmi collection and fix assertions in paypal remove mandates from nmi collection and fix assertions in paypal
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json index ad1de26c594..2161cc26a05 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json @@ -12,11 +12,9 @@ "Scenario8-Create a failure card payment with confirm true", "Scenario9-Update amount with automatic capture", "Scenario9a-Update amount with manual capture", - "Scenario10-Create a mandate and recurring payment", - "Scenario11-Refund recurring payment", - "Scenario12-Add card flow", - "Scenario13-Don't Pass CVV for save card flow and verify success payment", - "Scenario14-Save card payment with manual capture", - "Scenario15-Create payment without customer_id and with billing address and shipping address" + "Scenario10-Add card flow", + "Scenario11-Don't Pass CVV for save card flow and verify success payment", + "Scenario12-Save card payment with manual capture", + "Scenario13-Create payment without customer_id and with billing address and shipping address" ] } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json deleted file mode 100644 index 28591b45430..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Payments - Retrieve", - "Recurring Payments - Create", - "Payments - Retrieve-copy" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js deleted file mode 100644 index e72bc84b8cf..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js +++ /dev/null @@ -1,87 +0,0 @@ -// 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" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", - function () { - pm.expect(jsonData.status).to.eql("processing"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json deleted file mode 100644 index c3143943700..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "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": "{{random_number}}", - "currency": "USD", - "confirm": true, - "capture_method": "automatic", - "capture_on": "2022-09-10T10:11:12Z", - "amount_to_capture": "{{random_number}}", - "customer_id": "StripeCustomer", - "email": "guest@example.com", - "name": "John Doe", - "phone": "999999999", - "phone_country_code": "+65", - "description": "Its my first payment request", - "authentication_type": "no_three_ds", - "return_url": "https://duck.com", - "payment_method": "card", - "payment_method_data": { - "card": { - "card_number": "4111111111111111", - "card_exp_month": "10", - "card_exp_year": "69", - "card_holder_name": "joseph Doe", - "card_cvc": "123" - } - }, - "setup_future_usage": "off_session", - "mandate_data": { - "customer_acceptance": { - "acceptance_type": "offline", - "accepted_at": "1963-05-03T04:07:52.723Z", - "online": { - "ip_address": "127.0.0.1", - "user_agent": "amet irure esse" - } - }, - "mandate_type": { - "single_use": { - "amount": 100000, - "currency": "USD" - } - } - }, - "customer_acceptance": { - "acceptance_type": "offline", - "accepted_at": "1963-05-03T04:07:52.723Z", - "online": { - "ip_address": "127.0.0.1", - "user_agent": "amet irure esse" - } - }, - "billing": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John" - } - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John" - } - }, - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "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/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js deleted file mode 100644 index db584da2266..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js +++ /dev/null @@ -1,87 +0,0 @@ -// 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 "Succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js deleted file mode 100644 index db584da2266..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,87 +0,0 @@ -// 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 "Succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js deleted file mode 100644 index ce36d5ed1d6..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js +++ /dev/null @@ -1,95 +0,0 @@ -// 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" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", - function () { - pm.expect(jsonData.status).to.eql("processing"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); - -// Response body should have "payment_method_data" -pm.test( - "[POST]::/payments - Content check if 'payment_method_data' exists", - function () { - pm.expect(typeof jsonData.payment_method_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json deleted file mode 100644 index 44e6fbdf667..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "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": "{{random_number}}", - "currency": "USD", - "confirm": true, - "capture_method": "automatic", - "capture_on": "2022-09-10T10:11:12Z", - "amount_to_capture": "{{random_number}}", - "customer_id": "StripeCustomer", - "email": "guest@example.com", - "name": "John Doe", - "phone": "999999999", - "phone_country_code": "+65", - "description": "Its my first payment request", - "authentication_type": "no_three_ds", - "return_url": "https://duck.com", - "mandate_id": "{{mandate_id}}", - "off_session": true, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John" - } - }, - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "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/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json deleted file mode 100644 index e8b3174bc0e..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Payments - Retrieve", - "Recurring Payments - Create", - "Payments - Retrieve-copy", - "Refunds - Create", - "Refunds - Retrieve" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js deleted file mode 100644 index ffa879c31d6..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js +++ /dev/null @@ -1,90 +0,0 @@ -// 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.", - ); -} - -// Response body should have value "processing" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", - function () { - pm.expect(jsonData.status).to.eql("processing"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json deleted file mode 100644 index d7511caf779..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "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": "{{random_number}}", - "currency": "USD", - "confirm": true, - "capture_method": "automatic", - "capture_on": "2022-09-10T10:11:12Z", - "amount_to_capture": "{{random_number}}", - "customer_id": "StripeCustomer", - "email": "guest@example.com", - "name": "John Doe", - "phone": "999999999", - "phone_country_code": "+65", - "description": "Its my first payment request", - "authentication_type": "no_three_ds", - "return_url": "https://duck.com", - "payment_method": "card", - "payment_method_data": { - "card": { - "card_number": "4111111111111111", - "card_exp_month": "10", - "card_exp_year": "69", - "card_holder_name": "joseph Doe", - "card_cvc": "123" - } - }, - "setup_future_usage": "off_session", - "mandate_data": { - "customer_acceptance": { - "acceptance_type": "offline", - "accepted_at": "1963-05-03T04:07:52.723Z", - "online": { - "ip_address": "127.0.0.1", - "user_agent": "amet irure esse" - } - }, - "mandate_type": { - "single_use": { - "amount": 100000, - "currency": "USD" - } - } - }, - "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" - } - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John" - } - }, - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "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/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js deleted file mode 100644 index db584da2266..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js +++ /dev/null @@ -1,87 +0,0 @@ -// 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 "Succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js deleted file mode 100644 index db584da2266..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,87 +0,0 @@ -// 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 "Succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js deleted file mode 100644 index 500c24ec909..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js +++ /dev/null @@ -1,98 +0,0 @@ -// 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.", - ); -} - -// Response body should have value "processing" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", - function () { - pm.expect(jsonData.status).to.eql("processing"); - }, - ); -} - -// Response body should have "mandate_id" -pm.test( - "[POST]::/payments - Content check if 'mandate_id' exists", - function () { - pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true; - }, -); - -// Response body should have "mandate_data" -pm.test( - "[POST]::/payments - Content check if 'mandate_data' exists", - function () { - pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true; - }, -); - -// Response body should have "payment_method_data" -pm.test( - "[POST]::/payments - Content check if 'payment_method_data' exists", - function () { - pm.expect(typeof jsonData.payment_method_data !== "undefined").to.be.true; - }, -); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json deleted file mode 100644 index 44e6fbdf667..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "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": "{{random_number}}", - "currency": "USD", - "confirm": true, - "capture_method": "automatic", - "capture_on": "2022-09-10T10:11:12Z", - "amount_to_capture": "{{random_number}}", - "customer_id": "StripeCustomer", - "email": "guest@example.com", - "name": "John Doe", - "phone": "999999999", - "phone_country_code": "+65", - "description": "Its my first payment request", - "authentication_type": "no_three_ds", - "return_url": "https://duck.com", - "mandate_id": "{{mandate_id}}", - "off_session": true, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John" - } - }, - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "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/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js deleted file mode 100644 index 85957914aa2..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js +++ /dev/null @@ -1,53 +0,0 @@ -// 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.", - ); -} - -// Response body should have value "pending" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'pending'", - function () { - pm.expect(jsonData.status).to.eql("pending"); - }, - ); -} - -// Response body should have value for "amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'", - function () { - pm.expect(jsonData.amount).to.eql(amount); - }, - ); -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json deleted file mode 100644 index c4e7e01345d..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "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_id": "{{payment_id}}", - "amount": "{{amount}}", - "reason": "Customer returned product", - "refund_type": "instant", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js deleted file mode 100644 index 1c5c9e16c6f..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js +++ /dev/null @@ -1,53 +0,0 @@ -// Get the value of 'amount' from the environment -const refund_amount = pm.environment.get("amount"); - -// 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.", - ); -} - -// Response body should have value "succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have value for "refund_amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'", - function () { - pm.expect(jsonData.amount).to.eql(refund_amount); - }, - ); -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/request.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/response.json rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js deleted file mode 100644 index 30d9fbf35a0..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js +++ /dev/null @@ -1 +0,0 @@ -pm.environment.set("random_number", _.random(100, 100000)); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js deleted file mode 100644 index 30d9fbf35a0..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js +++ /dev/null @@ -1 +0,0 @@ -pm.environment.set("random_number", _.random(100, 100000)); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json deleted file mode 100644 index b9ebc1be4aa..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "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/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json deleted file mode 100644 index b9ebc1be4aa..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "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/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json deleted file mode 100644 index b9ebc1be4aa..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "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/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json deleted file mode 100644 index 6c28619e856..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js deleted file mode 100644 index 30d9fbf35a0..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js +++ /dev/null @@ -1 +0,0 @@ -pm.environment.set("random_number", _.random(100, 100000)); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json deleted file mode 100644 index eb871bbcb9b..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.prerequest.js", "event.test.js"] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js deleted file mode 100644 index 30d9fbf35a0..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js +++ /dev/null @@ -1 +0,0 @@ -pm.environment.set("random_number", _.random(100, 100000)); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json deleted file mode 100644 index b9ebc1be4aa..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "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/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js b/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js index 57900d52342..1de22fee9be 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js +++ b/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js @@ -18,7 +18,7 @@ pm.test("[POST]::/payments - Response has JSON Body", function () { let jsonData = {}; try { jsonData = pm.response.json(); -} catch (e) {} +} catch (e) { } // pm.collectionVariables - Set payment_id as variable for jsonData.payment_id if (jsonData?.payment_id) { @@ -72,9 +72,9 @@ if (jsonData?.status) { // Response body should have value "requires_confirmation" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'error_code' matches 'UNPROCESSABLE_ENTITY'", + "[POST]::/payments - Content check if value for 'error_code' matches 'VALIDATION_ERROR'", function () { - pm.expect(jsonData.error_code).to.eql("UNPROCESSABLE_ENTITY"); + pm.expect(jsonData.error_code).to.eql("VALIDATION_ERROR"); }, ); } diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json index fa1dbac954f..ab493bc92ba 100644 --- a/postman/collection-json/nmi.postman_collection.json +++ b/postman/collection-json/nmi.postman_collection.json @@ -6504,1368 +6504,7 @@ ] }, { - "name": "Scenario10-Create a mandate and recurring payment", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"processing\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// 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 \"Succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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 payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Recurring Payments - Create", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"processing\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"payment_method_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "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-copy", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"Succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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 payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "Scenario11-Refund recurring payment", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// 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.\",", - " );", - "}", - "", - "// Response body should have value \"processing\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// 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 \"Succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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 payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Recurring Payments - Create", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// 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.\",", - " );", - "}", - "", - "// Response body should have value \"processing\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"payment_method_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "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-copy", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"Succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "" - ], - "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 payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "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.\",", - " );", - "}", - "", - "// Response body should have value \"pending\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"pending\");", - " },", - " );", - "}", - "", - "// Response body should have value for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - " },", - " );", - "}", - "" - ], - "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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Get the value of 'amount' from the environment", - "const refund_amount = pm.environment.get(\"amount\");", - "", - "// 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.\",", - " );", - "}", - "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have value for \"refund_amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(refund_amount);", - " },", - " );", - "}", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - } - ] - }, - { - "name": "Scenario12-Add card flow", + "name": "Scenario10-Add card flow", "item": [ { "name": "Payments - Create", @@ -8465,7 +7104,7 @@ ] }, { - "name": "Scenario13-Don't Pass CVV for save card flow and verify success payment", + "name": "Scenario11-Don't Pass CVV for save card flow and verify success payment", "item": [ { "name": "Payments - Create", @@ -8970,7 +7609,7 @@ ] }, { - "name": "Scenario14-Save card payment with manual capture", + "name": "Scenario12-Save card payment with manual capture", "item": [ { "name": "Payments - Create", @@ -10338,7 +8977,7 @@ ] }, { - "name": "Scenario15-Create payment without customer_id and with billing address and shipping address", + "name": "Scenario13-Create payment without customer_id and with billing address and shipping address", "item": [ { "name": "Payments - Create", diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json index 4270035992f..bcb508da4c0 100644 --- a/postman/collection-json/paypal.postman_collection.json +++ b/postman/collection-json/paypal.postman_collection.json @@ -5402,7 +5402,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) {}", + "} catch (e) { }", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -5456,9 +5456,9 @@ "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'error_code' matches 'UNPROCESSABLE_ENTITY'\",", + " \"[POST]::/payments - Content check if value for 'error_code' matches 'VALIDATION_ERROR'\",", " function () {", - " pm.expect(jsonData.error_code).to.eql(\"UNPROCESSABLE_ENTITY\");", + " pm.expect(jsonData.error_code).to.eql(\"VALIDATION_ERROR\");", " },", " );", "}",
2024-03-19T11:03:12Z
## Description <!-- Describe your changes in detail --> touched 2 collections namely, NMI and PayPal: - fixed assertion in PayPal which broke due to [this](https://github.com/juspay/hyperswitch/commit/fc81f90f6168dc6e08cbfacdda0f59e99def07da) commit - removed mandate collection from NMI as it is not supported closes #4127 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Reduce reds. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - NMI <img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/53f628e9-693f-4794-8ed9-64f53afb82be"> - PayPal <img width="499" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/b6c4f789-1b85-4dbf-bb6d-1dcafc6420b0"> `.json` files are auto-generate from `dir`
944089d6914cb6bece9056f78b9aabf90e485151
- NMI <img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/53f628e9-693f-4794-8ed9-64f53afb82be"> - PayPal <img width="499" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/b6c4f789-1b85-4dbf-bb6d-1dcafc6420b0"> `.json` files are auto-generate from `dir`
[ "postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json", "postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/.meta.json", "postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/.event.meta.json", ...
juspay/hyperswitch
juspay__hyperswitch-4163
Bug: feat: create an api to get countries and currencies for a connector and pmt Currently there is no way to set countries and currencies for a particular connector and payment method type. This api should give the list of countries and currencies supported by a given connector and payment method type combination. This will be used by frontend to set filters.
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 346ee34b2cf..b26ee0ae68e 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -3,8 +3,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{ payment_methods::{ CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse, - DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest, - PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, + DefaultPaymentMethod, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, + PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse, + PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters, @@ -131,6 +132,9 @@ impl ApiEventMetric for PaymentMethodListRequest { } } +impl ApiEventMetric for ListCountriesCurrenciesRequest {} + +impl ApiEventMetric for ListCountriesCurrenciesResponse {} impl ApiEventMetric for PaymentMethodListResponse {} impl ApiEventMetric for CustomerDefaultPaymentMethodResponse { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 37580edbc71..f08a793ebf5 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use cards::CardNumber; use common_utils::{ @@ -914,6 +914,26 @@ pub struct TokenizedCardValue1 { pub card_token: Option<String>, } +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ListCountriesCurrenciesRequest { + pub connector: api_enums::Connector, + pub payment_method_type: api_enums::PaymentMethodType, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ListCountriesCurrenciesResponse { + pub currencies: HashSet<api_enums::Currency>, + pub countries: HashSet<CountryCodeWithName>, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)] +pub struct CountryCodeWithName { + pub code: api_enums::CountryAlpha2, + pub name: api_enums::Country, +} + #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index a1156366d33..2ba3551c1e3 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1581,6 +1581,7 @@ pub enum DisputeStatus { serde::Deserialize, serde::Serialize, strum::Display, + strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 289654f93ed..2a6c29ce803 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,8 +7,9 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, - CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes, + BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, + CustomerDefaultPaymentMethodResponse, ListCountriesCurrenciesRequest, + ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, @@ -30,6 +31,7 @@ use domain::CustomerUpdate; use error_stack::{report, IntoReport, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; +use strum::IntoEnumIterator; use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, @@ -3606,3 +3608,59 @@ pub async fn create_encrypted_payment_method_data( pm_data_encrypted } + +pub async fn list_countries_currencies_for_connector_payment_method( + state: routes::AppState, + req: ListCountriesCurrenciesRequest, +) -> errors::RouterResponse<ListCountriesCurrenciesResponse> { + Ok(services::ApplicationResponse::Json( + list_countries_currencies_for_connector_payment_method_util( + state.conf.pm_filters.clone(), + req.connector, + req.payment_method_type, + ) + .await, + )) +} + +// This feature will be more efficient as a WASM function rather than as an API. +// So extracting this logic to a separate function so that it can be used in WASM as well. +pub async fn list_countries_currencies_for_connector_payment_method_util( + connector_filters: settings::ConnectorFilters, + connector: api_enums::Connector, + payment_method_type: api_enums::PaymentMethodType, +) -> ListCountriesCurrenciesResponse { + let payment_method_type = + settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type); + + let (currencies, country_codes) = connector_filters + .0 + .get(&connector.to_string()) + .and_then(|filter| filter.0.get(&payment_method_type)) + .map(|filter| (filter.currency.clone(), filter.country.clone())) + .unwrap_or_else(|| { + connector_filters + .0 + .get("default") + .and_then(|filter| filter.0.get(&payment_method_type)) + .map_or((None, None), |filter| { + (filter.currency.clone(), filter.country.clone()) + }) + }); + + let currencies = + currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>()); + let country_codes = + country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>()); + + ListCountriesCurrenciesResponse { + currencies, + countries: country_codes + .into_iter() + .map(|country_code| CountryCodeWithName { + code: country_code, + name: common_enums::Country::from_alpha2(country_code), + }) + .collect(), + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 7d6b6c8ad28..f67b82faf3f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -19,8 +19,6 @@ use tokio::sync::oneshot; #[cfg(feature = "olap")] use super::blocklist; -#[cfg(any(feature = "olap", feature = "oltp"))] -use super::currency; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; #[cfg(feature = "payouts")] @@ -39,8 +37,10 @@ use super::{ use super::{cache::*, health::*}; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; +#[cfg(any(feature = "olap", feature = "oltp"))] +use super::{currency, payment_methods::*}; #[cfg(feature = "oltp")] -use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; +use super::{ephemeral_key::*, webhooks::*}; use crate::configs::secrets_transformers; #[cfg(all(feature = "frm", feature = "oltp"))] use crate::routes::fraud_check as frm_routes; @@ -738,24 +738,39 @@ impl Payouts { pub struct PaymentMethods; -#[cfg(feature = "oltp")] +#[cfg(any(feature = "olap", feature = "oltp"))] impl PaymentMethods { pub fn server(state: AppState) -> Scope { - web::scope("/payment_methods") - .app_data(web::Data::new(state)) - .service( - web::resource("") - .route(web::post().to(create_payment_method_api)) - .route(web::get().to(list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later - ) - .service( - web::resource("/{payment_method_id}") - .route(web::get().to(payment_method_retrieve_api)) - .route(web::post().to(payment_method_update_api)) - .route(web::delete().to(payment_method_delete_api)), - ) - .service(web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create))) - .service(web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token))) + let mut route = web::scope("/payment_methods").app_data(web::Data::new(state)); + #[cfg(feature = "olap")] + { + route = route.service( + web::resource("/filter") + .route(web::get().to(list_countries_currencies_for_connector_payment_method)), + ); + } + #[cfg(feature = "oltp")] + { + route = route + .service( + web::resource("") + .route(web::post().to(create_payment_method_api)) + .route(web::get().to(list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later + ) + .service( + web::resource("/{payment_method_id}") + .route(web::get().to(payment_method_retrieve_api)) + .route(web::post().to(payment_method_update_api)) + .route(web::delete().to(payment_method_delete_api)), + ) + .service( + web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)), + ) + .service( + web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)), + ) + } + route } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 43802d24451..fd7bdb9019e 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -97,6 +97,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodsUpdate | Flow::PaymentMethodsDelete | Flow::ValidatePaymentMethod + | Flow::ListCountriesCurrencies | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods, Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 1e2e66d583c..7ef20994e2e 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -8,7 +8,7 @@ use time::PrimitiveDateTime; use super::app::AppState; use crate::{ core::{api_locking, errors, payment_methods::cards}, - services::{api, authentication as auth}, + services::{api, authentication as auth, authorization::permissions::Permission}, types::{ api::payment_methods::{self, PaymentMethodId}, storage::payment_method::PaymentTokenData, @@ -262,6 +262,35 @@ pub async fn payment_method_delete_api( .await } +#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] +pub async fn list_countries_currencies_for_connector_payment_method( + state: web::Data<AppState>, + req: HttpRequest, + query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, +) -> HttpResponse { + let flow = Flow::ListCountriesCurrencies; + let payload = query_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _auth: auth::AuthenticationData, req| { + cards::list_countries_currencies_for_connector_payment_method(state, req) + }, + #[cfg(not(feature = "release"))] + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + req.headers(), + ), + #[cfg(feature = "release")] + &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] pub async fn default_payment_method_set_api( state: web::Data<AppState>, @@ -297,7 +326,6 @@ pub async fn default_payment_method_set_api( )) .await } - #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 642e94ad69e..13c9ec61f2a 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,11 +1,11 @@ pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, - GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate, - PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest, - PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, - TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, - TokenizedWalletValue1, TokenizedWalletValue2, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, + PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, + PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, + PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, + TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, }; use error_stack::report; diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index b521acbdcdc..635c6268d67 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -117,6 +117,8 @@ pub enum Flow { CustomerPaymentMethodsList, /// List Customers for a merchant CustomersList, + /// Retrieve countries and currencies for connector and payment method + ListCountriesCurrencies, /// Payment methods retrieve flow. PaymentMethodsRetrieve, /// Payment methods update flow.
2024-03-19T09:33:32Z
## Description Make a api to fetch the countries and currencies supported by a particular connector. This api will be used by the dashboard to restrict payment methods to specific countries/currencies. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4163 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - When the filters are set for the combination of connector and payment method type ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=affirm' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "USD" ], "countries": [ { "code": "US", "name": "UnitedStatesOfAmerica" } ] } ``` - When the filters are not set for the given combination, we will use default filters to get the list ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "BRL", "INR", "EUR", "JPY", "CHF", "USD", "PLN", "MYR", "PHP", "SGD", "THB", "SEK", "RUB", "CAD", "HKD", "CZK", "NOK", "NZD", "HUF", "GBP", "AUD", "DKK", "MXN" ], "countries": [ { "code": "DE", "name": "Germany" }, ... { "code": "ZA", "name": "SouthAfrica" } ] } ``` - If the filters are not set in default also, then the list of all countries and currencies will be sent - When the filters are not set for the given combination, we will use default filters to get the list ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "XPF", ... "ZMW" ], "countries": [ { "code": "DE", "name": "Germany" }, ... { "code": "ZA", "name": "SouthAfrica" } ] } ```
b8c927593a85792588e582bf25f2daadfa5f7fb0
- When the filters are set for the combination of connector and payment method type ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=affirm' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "USD" ], "countries": [ { "code": "US", "name": "UnitedStatesOfAmerica" } ] } ``` - When the filters are not set for the given combination, we will use default filters to get the list ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "BRL", "INR", "EUR", "JPY", "CHF", "USD", "PLN", "MYR", "PHP", "SGD", "THB", "SEK", "RUB", "CAD", "HKD", "CZK", "NOK", "NZD", "HUF", "GBP", "AUD", "DKK", "MXN" ], "countries": [ { "code": "DE", "name": "Germany" }, ... { "code": "ZA", "name": "SouthAfrica" } ] } ``` - If the filters are not set in default also, then the list of all countries and currencies will be sent - When the filters are not set for the given combination, we will use default filters to get the list ``` curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \ --header 'Authorization: Bearer JWT' \ ``` ``` { "currencies": [ "XPF", ... "ZMW" ], "countries": [ { "code": "DE", "name": "Germany" }, ... { "code": "ZA", "name": "SouthAfrica" } ] } ```
[ "crates/api_models/src/events/payment.rs", "crates/api_models/src/payment_methods.rs", "crates/common_enums/src/enums.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/payment_methods.rs", "cra...
juspay/hyperswitch
juspay__hyperswitch-4178
Bug: [FIX] fix 404 when not sending payment_id to compatibility layer
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 87560032ea4..56bcb2d58d0 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -7,7 +7,8 @@ use router_env::{instrument, tracing, Flow, Tag}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking::GetLockingInput, payment_methods::Oss, payments}, - logger, routes, + logger, + routes::{self, payments::get_or_generate_payment_id}, services::{api, authentication as auth}, types::api as api_types, }; @@ -26,15 +27,19 @@ pub async fn payment_intents_create( Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; + tracing::Span::current().record("payment_id", &payload.id.clone().unwrap_or_default()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); - let create_payment_req: payment_types::PaymentsRequest = match payload.try_into() { + let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; + if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) { + return api::log_and_return_error_response(err); + } let flow = Flow::PaymentsCreate; let locking_action = create_payment_req.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::<
2024-03-19T09:18:36Z
## Description <!-- Describe your changes in detail --> Fixed the bug where `compatibility` layer would throw 404 if `payment_id` is not sent. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - This fixes the bug where `compatibility` layer would throw 404 if `payment_id` is not sent in request ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a payment without passing the `payment_id` to stripe compatibility layer ```bash curl --location 'http://localhost:8080/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --header 'api-key: dev_N1nUguE0Mue3z1CrAMAt5ZahpeFGVcwzuiBM9mM6DR9ClR4r5uFrKfI7UcdDnToM' \ --data-urlencode 'amount=2000' \ --data-urlencode 'currency=AED' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=card' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=4242424242424242' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=12' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=2030' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \ --data-urlencode 'connector%5B%5D=stripe' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'description=Card Payment' \ --data-urlencode 'off_session=true' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Buser_agent%5D=helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Bip_address%5D=123.32.25.123' \ --data-urlencode 'mandate_data%5Bamount%5D=20877' \ --data-urlencode 'setup_future_usage=off_session' \ --data-urlencode 'return_url=https://juspay.in' \ --data-urlencode 'metadata%5Btxn_Id%5D=sahkal_payment' \ --data-urlencode 'metadata%5BtxnUuid%5D=94hfdmoakosdkifdhaisl' \ --data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \ --data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=sahkal' ``` - It should return 200 with auto generated `payment_id`
a843713126cea102064b342b6fc82429d89d758a
- Create a payment without passing the `payment_id` to stripe compatibility layer ```bash curl --location 'http://localhost:8080/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --header 'api-key: dev_N1nUguE0Mue3z1CrAMAt5ZahpeFGVcwzuiBM9mM6DR9ClR4r5uFrKfI7UcdDnToM' \ --data-urlencode 'amount=2000' \ --data-urlencode 'currency=AED' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=card' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=4242424242424242' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=12' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=2030' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \ --data-urlencode 'connector%5B%5D=stripe' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'description=Card Payment' \ --data-urlencode 'off_session=true' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Buser_agent%5D=helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Bip_address%5D=123.32.25.123' \ --data-urlencode 'mandate_data%5Bamount%5D=20877' \ --data-urlencode 'setup_future_usage=off_session' \ --data-urlencode 'return_url=https://juspay.in' \ --data-urlencode 'metadata%5Btxn_Id%5D=sahkal_payment' \ --data-urlencode 'metadata%5BtxnUuid%5D=94hfdmoakosdkifdhaisl' \ --data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \ --data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=sahkal' ``` - It should return 200 with auto generated `payment_id`
[ "crates/router/src/compatibility/stripe/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3227
Bug: [FEATURE] : Billwerk payments integration ### Feature Description Billwerk Payments is a payment gateway provider focused on Northern Europe countries. ### Possible Implementation Product: [https://www.billwerk.plus/payments/](https://www.billwerk.plus/payments/) Docs: [https://docs.reepay.com/](https://docs.reepay.com/) ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/config.example.toml b/config/config.example.toml index 81cd78f7244..ee868beb092 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -170,6 +170,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" diff --git a/config/development.toml b/config/development.toml index 66ed76c8f3c..8d18e63122f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -97,6 +97,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", @@ -165,6 +166,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7677fc4582d..ceb00ff212e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -104,6 +104,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" @@ -176,6 +177,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index f712871abe1..b29377886d5 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -78,6 +78,7 @@ pub enum Connector { Authorizedotnet, Bambora, Bankofamerica, + // Billwerk, Added as template code for future usage Bitpay, Bluesnap, Boku, @@ -165,6 +166,7 @@ impl Connector { | Self::Authorizedotnet | Self::Bambora | Self::Bankofamerica + // | Self::Billwerk Added as template code for future usage | Self::Bitpay | Self::Bluesnap | Self::Boku @@ -221,6 +223,7 @@ impl Connector { | Self::Authorizedotnet | Self::Bambora | Self::Bankofamerica + // | Self::Billwerk Added as template for future usage | Self::Bitpay | Self::Bluesnap | Self::Boku diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 89ca80e72b3..65842a4203d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -115,6 +115,7 @@ pub enum RoutableConnectors { Airwallex, Authorizedotnet, Bankofamerica, + // Billwerk, Added as template code for future usage Bitpay, Bambora, Bluesnap, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 2ef80f8f2f6..74317319f50 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -116,6 +116,7 @@ pub struct ConnectorConfig { pub airwallex: Option<ConnectorTomlConfig>, pub authorizedotnet: Option<ConnectorTomlConfig>, pub bankofamerica: Option<ConnectorTomlConfig>, + pub billwerk: Option<ConnectorTomlConfig>, pub bitpay: Option<ConnectorTomlConfig>, pub bluesnap: Option<ConnectorTomlConfig>, pub boku: Option<ConnectorTomlConfig>, @@ -227,6 +228,7 @@ impl ConnectorConfig { Connector::Airwallex => Ok(connector_data.airwallex), Connector::Authorizedotnet => Ok(connector_data.authorizedotnet), Connector::Bankofamerica => Ok(connector_data.bankofamerica), + // Connector::Billwerk => Ok(connector_data.billwerk), Added as template code for future usage Connector::Bitpay => Ok(connector_data.bitpay), Connector::Bluesnap => Ok(connector_data.bluesnap), Connector::Boku => Ok(connector_data.boku), diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 2f87c5c21d7..d92812cee40 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -480,6 +480,7 @@ pub struct Connectors { pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bankofamerica: ConnectorParams, + pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index eccdf3f9ddf..d786ed4e31b 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,6 +4,7 @@ pub mod airwallex; pub mod authorizedotnet; pub mod bambora; pub mod bankofamerica; +pub mod billwerk; pub mod bitpay; pub mod bluesnap; pub mod boku; @@ -60,15 +61,15 @@ pub mod zen; pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet, - bambora::Bambora, bankofamerica::Bankofamerica, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, - braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, - cryptopay::Cryptopay, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim, - iatapay::Iatapay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, - nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, - payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu, placetopay::Placetopay, - powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, riskified::Riskified, - shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, - threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt, wise::Wise, - worldline::Worldline, worldpay::Worldpay, zen::Zen, + bambora::Bambora, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, + bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode, + checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, + dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, globepay::Globepay, + gocardless::Gocardless, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mollie::Mollie, + multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, + opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu, + placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, + riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, + stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt, + wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen, }; diff --git a/crates/router/src/connector/billwerk.rs b/crates/router/src/connector/billwerk.rs new file mode 100644 index 00000000000..c7d81e06c32 --- /dev/null +++ b/crates/router/src/connector/billwerk.rs @@ -0,0 +1,561 @@ +pub mod transformers; + +use std::fmt::Debug; + +use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; +use transformers as billwerk; + +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, + headers, + services::{ + self, + request::{self, Mask}, + ConnectorIntegration, ConnectorValidation, + }, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, RequestContent, Response, + }, + utils::BytesExt, +}; + +#[derive(Debug, Clone)] +pub struct Billwerk; + +impl api::Payment for Billwerk {} +impl api::PaymentSession for Billwerk {} +impl api::ConnectorAccessToken for Billwerk {} +impl api::MandateSetup for Billwerk {} +impl api::PaymentAuthorize for Billwerk {} +impl api::PaymentSync for Billwerk {} +impl api::PaymentCapture for Billwerk {} +impl api::PaymentVoid for Billwerk {} +impl api::Refund for Billwerk {} +impl api::RefundExecute for Billwerk {} +impl api::RefundSync for Billwerk {} +impl api::PaymentToken for Billwerk {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Billwerk +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + 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(), + 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 Billwerk { + fn id(&self) -> &'static str { + "billwerk" + } + + 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 settings::Connectors) -> &'a str { + connectors.billwerk.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = billwerk::BillwerkAuthType::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: billwerk::BillwerkErrorResponse = res + .response + .parse_struct("BillwerkErrorResponse") + .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 Billwerk { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Billwerk +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Billwerk +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Billwerk +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Billwerk +{ + 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, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = billwerk::BillwerkRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = billwerk::BillwerkPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_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, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("Billwerk PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Billwerk +{ + 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, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("billwerk PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Billwerk +{ + 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, + _connectors: &settings::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> { + 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, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: billwerk::BillwerkPaymentsResponse = res + .response + .parse_struct("Billwerk PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Billwerk +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Billwerk +{ + 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>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = billwerk::BillwerkRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = billwerk::BillwerkRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(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)?) + .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: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: billwerk::RefundResponse = res + .response + .parse_struct("billwerk RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Billwerk { + 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)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: billwerk::RefundResponse = res + .response + .parse_struct("billwerk RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Billwerk { + 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<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs new file mode 100644 index 00000000000..c6f025b7898 --- /dev/null +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -0,0 +1,244 @@ +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 +pub struct BillwerkRouterData<T> { + pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for BillwerkRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> 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, + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct BillwerkPaymentsRequest { + amount: i64, + card: BillwerkCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct BillwerkCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + api::PaymentMethodData::Card(req_card) => { + let card = BillwerkCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.to_owned(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct BillwerkAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for BillwerkAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::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 BillwerkPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<BillwerkPaymentStatus> for enums::AttemptStatus { + fn from(item: BillwerkPaymentStatus) -> Self { + match item { + BillwerkPaymentStatus::Succeeded => Self::Charged, + BillwerkPaymentStatus::Failed => Self::Failure, + BillwerkPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BillwerkPaymentsResponse { + status: BillwerkPaymentStatus, + id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, BillwerkPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BillwerkPaymentsResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct BillwerkRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&BillwerkRouterData<&types::RefundsRouterData<F>>> for BillwerkRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&types::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<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 BillwerkErrorResponse { + pub status_code: u16, + pub code: 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 2f546cfa5ac..a4be66242ee 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1739,6 +1739,10 @@ pub(crate) fn validate_auth_and_metadata_type( bankofamerica::transformers::BankOfAmericaAuthType::try_from(val)?; Ok(()) } + // api_enums::Connector::Billwerk => { + // billwerk::transformers::BillwerkAuthType::try_from(val)?; + // Ok(()) + // } Added as template code for future usage api_enums::Connector::Bitpay => { bitpay::transformers::BitpayAuthType::try_from(val)?; Ok(()) diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index fe4a504861d..6c952dc2593 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -145,9 +145,9 @@ impl<const T: u8> } default_imp_for_complete_authorize!( - connector::Threedsecureio, connector::Aci, connector::Adyen, + connector::Billwerk, connector::Bitpay, connector::Boku, connector::Cashtocode, @@ -176,6 +176,7 @@ default_imp_for_complete_authorize!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -211,13 +212,13 @@ impl<const T: u8> { } default_imp_for_webhook_source_verification!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Braintree, @@ -257,6 +258,7 @@ default_imp_for_webhook_source_verification!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -294,13 +296,13 @@ impl<const T: u8> } default_imp_for_create_customer!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -338,6 +340,7 @@ default_imp_for_create_customer!( connector::Shift4, connector::Signifyd, connector::Square, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -377,11 +380,11 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec } default_imp_for_connector_redirect_response!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Bitpay, connector::Bankofamerica, + connector::Billwerk, connector::Boku, connector::Cashtocode, connector::Coinbase, @@ -410,6 +413,7 @@ default_imp_for_connector_redirect_response!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Tsys, connector::Volt, connector::Wise, @@ -429,13 +433,13 @@ macro_rules! default_imp_for_connector_request_id { impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} default_imp_for_connector_request_id!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -474,6 +478,7 @@ default_imp_for_connector_request_id!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -514,13 +519,13 @@ impl<const T: u8> } default_imp_for_accept_dispute!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -560,6 +565,7 @@ default_imp_for_accept_dispute!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -619,13 +625,13 @@ impl<const T: u8> } default_imp_for_file_upload!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -663,6 +669,7 @@ default_imp_for_file_upload!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -701,13 +708,13 @@ impl<const T: u8> } default_imp_for_submit_evidence!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -745,6 +752,7 @@ default_imp_for_submit_evidence!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -783,13 +791,13 @@ impl<const T: u8> } default_imp_for_defend_dispute!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -828,6 +836,7 @@ default_imp_for_defend_dispute!( connector::Square, connector::Stax, connector::Stripe, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -866,11 +875,11 @@ impl<const T: u8> } default_imp_for_pre_processing_steps!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -905,6 +914,7 @@ default_imp_for_pre_processing_steps!( connector::Signifyd, connector::Square, connector::Stax, + connector::Threedsecureio, connector::Tsys, connector::Volt, connector::Wise, @@ -925,12 +935,12 @@ macro_rules! default_imp_for_payouts { impl<const T: u8> api::Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -971,6 +981,7 @@ default_imp_for_payouts!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1008,12 +1019,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_create!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1054,6 +1065,7 @@ default_imp_for_payouts_create!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1094,12 +1106,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1140,6 +1152,7 @@ default_imp_for_payouts_eligibility!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1177,12 +1190,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1223,6 +1236,7 @@ default_imp_for_payouts_fulfill!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1260,12 +1274,12 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( - connector::Threedsecureio, connector::Aci, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1306,6 +1320,7 @@ default_imp_for_payouts_cancel!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1343,13 +1358,13 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1390,6 +1405,7 @@ default_imp_for_payouts_quote!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1427,13 +1443,13 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1474,6 +1490,7 @@ default_imp_for_payouts_recipient!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1510,13 +1527,13 @@ impl<const T: u8> } default_imp_for_approve!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1557,6 +1574,7 @@ default_imp_for_approve!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1594,13 +1612,13 @@ impl<const T: u8> } default_imp_for_reject!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1641,6 +1659,7 @@ default_imp_for_reject!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1662,13 +1681,13 @@ macro_rules! default_imp_for_fraud_check { impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} default_imp_for_fraud_check!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1707,6 +1726,7 @@ default_imp_for_fraud_check!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1746,13 +1766,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_sale!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1791,6 +1811,7 @@ default_imp_for_frm_sale!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1830,13 +1851,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_checkout!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1875,6 +1896,7 @@ default_imp_for_frm_checkout!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1914,13 +1936,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_transaction!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -1959,6 +1981,7 @@ default_imp_for_frm_transaction!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -1998,13 +2021,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2043,6 +2066,7 @@ default_imp_for_frm_fulfillment!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2082,13 +2106,13 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_record_return!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2127,6 +2151,7 @@ default_imp_for_frm_record_return!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2164,13 +2189,13 @@ impl<const T: u8> } default_imp_for_incremental_authorization!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2210,6 +2235,7 @@ default_imp_for_incremental_authorization!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2245,13 +2271,13 @@ impl<const T: u8> { } default_imp_for_revoking_mandates!( - connector::Threedsecureio, connector::Aci, connector::Adyen, connector::Airwallex, connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, @@ -2290,6 +2316,7 @@ default_imp_for_revoking_mandates!( connector::Stax, connector::Stripe, connector::Shift4, + connector::Threedsecureio, connector::Trustpay, connector::Tsys, connector::Volt, @@ -2373,6 +2400,7 @@ default_imp_for_connector_authentication!( connector::Authorizedotnet, connector::Bambora, connector::Bankofamerica, + connector::Billwerk, connector::Bitpay, connector::Bluesnap, connector::Boku, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index cd9eee46eec..95a0989ac2b 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -328,6 +328,7 @@ impl ConnectorData { enums::Connector::Authorizedotnet => Ok(Box::new(&connector::Authorizedotnet)), enums::Connector::Bambora => Ok(Box::new(&connector::Bambora)), enums::Connector::Bankofamerica => Ok(Box::new(&connector::Bankofamerica)), + // enums::Connector::Billwerk => Ok(Box::new(&connector::Billwerk)), Added as template code for future usage enums::Connector::Bitpay => Ok(Box::new(&connector::Bitpay)), enums::Connector::Bluesnap => Ok(Box::new(&connector::Bluesnap)), enums::Connector::Boku => Ok(Box::new(&connector::Boku)), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 29774be91af..2f0c9479914 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -188,6 +188,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Authorizedotnet => Self::Authorizedotnet, api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bankofamerica => Self::Bankofamerica, + // api_enums::Connector::Billwerk => Self::Billwerk, Added as template code for future usage api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, api_enums::Connector::Boku => Self::Boku, diff --git a/crates/router/tests/connectors/billwerk.rs b/crates/router/tests/connectors/billwerk.rs new file mode 100644 index 00000000000..1dec066e5d2 --- /dev/null +++ b/crates/router/tests/connectors/billwerk.rs @@ -0,0 +1,421 @@ +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct BillwerkTest; +impl ConnectorActions for BillwerkTest {} +impl utils::Connector for BillwerkTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Billwerk; + types::api::ConnectorData { + connector: Box::new(&Billwerk), + // Added as Dummy connector as template code is added for future usage + connector_name: types::Connector::DummyConnector1, + get_token: types::api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .billwerk + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "billwerk".to_string() + } +} + +static CONNECTOR: BillwerkTest = BillwerkTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenerios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 8db743d6098..eb428a36cb9 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -13,6 +13,8 @@ mod authorizedotnet; mod bambora; #[cfg(feature = "dummy_connector")] mod bankofamerica; +#[cfg(feature = "dummy_connector")] +mod billwerk; mod bitpay; mod bluesnap; mod boku; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 3f78ff7f491..bd17f279c2d 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -198,3 +198,7 @@ key1= "Trankey" [threedsecureio] api_key="API Key" + + +[billwerk] +api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index a2753a2c517..34a5e35928d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -18,6 +18,7 @@ pub struct ConnectorAuthentication { pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, pub bankofamerica: Option<SignatureKey>, + pub billwerk: Option<HeaderKey>, pub bitpay: Option<HeaderKey>, pub bluesnap: Option<BodyKey>, pub boku: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6dfd921a251..9a9a7606ca1 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -71,6 +71,7 @@ applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +billwerk.base_url = "https://api.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" @@ -142,6 +143,7 @@ cards = [ "authorizedotnet", "bambora", "bankofamerica", + "billwerk", "bitpay", "bluesnap", "boku", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 2be49d123b0..9098be40e21 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-03-19T05:51:33Z
## Description <!-- Describe your changes in detail --> Add Billwerk Template connector code https://reference.reepay.com/api/ ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3227 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Template code added hence no testing required
027080683d00a616e6dec40f57a4586951d76b09
Template code added hence no testing required
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/enums.rs", "crates/common_enums/src/enums.rs", "crates/connector_configs/src/connector.rs", "crates/router/src/configs/settings.rs", "crates/router/src/connector.rs", "crates/router/src/conn...
juspay/hyperswitch
juspay__hyperswitch-4121
Bug: [REFACTOR]: update Stripe API version in the API headers ### Bug Description Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. The current API version is not the compatible with our implementation. So we need to update the version according to current implementation. ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index dd8fc845e28..b85247607e0 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -34,7 +34,7 @@ use crate::{ pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; - pub const STRIPE_VERSION: &str = "2023-10-16"; + pub const STRIPE_VERSION: &str = "2022-11-15"; } pub struct StripeAuthType {
2024-03-18T17:50:58Z
## Description Fixes https://github.com/juspay/hyperswitch/issues/4121 Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. The current API version is not the compatible with our implementation. So we need to update the version according to current implementation. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? 1. Run whole Stripe Postman collection 2. Create a stripe Card Payment Request ``` { "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Response ``` { "payment_id": "pay_cmmd8900wIRqd11y6kUL", "merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL", "created": "2024-03-15T10:59:51.115Z", "currency": "INR", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710500391, "expires": 1710503991, "secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "payment_link": null, "profile_id": "pro_2x6hcEAjCQmaYxIpxO5V", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:14:51.115Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id` For that payment check the header-info , API-Version should be `"2022-11-15"` Do Paymnet Retrieve for same Payment ID Do a Refund ``` { "payment_id": "{{payment_id}}", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Do Refund Retrieve 3. Create a payment with capture = manual ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Capture it for same PI Payment should get succeeded with `status = succeeded` Again create a payment for capture = manual Void a Paymnet - Payment should get cancelled with `status = cancelled` 4. Create a O Auth mandate payment with stripe cards ``` { "amount": 0, "currency": "USD", "confirm": true, "setup_future_usage": "off_session", "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "payment_type": "setup_mandate", "payment_method": "card", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 7000, "currency": "USD" } } }, "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Chaser", "last_name": "Dough" }, "email": "example@juspay.in" } } ``` Response of 0 auth mandate ``` { "payment_id": "pay_L8pXs9YkASVJBvSSd0M2", "merchant_id": "postman_merchant_GHAction_5a2737e9-c107-411c-b458-8401b98e91ea", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "stripe", "client_secret": "pay_L8pXs9YkASVJBvSSd0M2_secret_oeTWqzB1O8kfVjzCeDDh", "created": "2024-03-19T06:56:47.885Z", "currency": "USD", "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "description": null, "refunds": null, "disputes": null, "mandate_id": "man_e0ADcjvb5OXgrGw1nF73", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 7000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Chaser", "last_name": "Dough" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "created_at": 1710831407, "expires": 1710835007, "secret": "epk_0ac0213b300e4d5f87c98645f96f5b6e" }, "manual_retry_allowed": false, "connector_transaction_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu", "payment_link": null, "profile_id": "pro_dHIsgCLvmZZcFRgkt3xE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mJiXEB1oLi5HXKhWCt9A", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-19T07:11:47.885Z", "fingerprint": null, "payment_method_id": "pm_SO8UJG7uDvc8oC2KgDAc", "payment_method_status": null } ``` Check the version after the payment in stripe dashboard. API-Version should be `"2022-11-15"`
fcfd567bfe55747dcb05c88def96373a707f8c78
1. Run whole Stripe Postman collection 2. Create a stripe Card Payment Request ``` { "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Response ``` { "payment_id": "pay_cmmd8900wIRqd11y6kUL", "merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL", "created": "2024-03-15T10:59:51.115Z", "currency": "INR", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710500391, "expires": 1710503991, "secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "payment_link": null, "profile_id": "pro_2x6hcEAjCQmaYxIpxO5V", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:14:51.115Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id` For that payment check the header-info , API-Version should be `"2022-11-15"` Do Paymnet Retrieve for same Payment ID Do a Refund ``` { "payment_id": "{{payment_id}}", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Do Refund Retrieve 3. Create a payment with capture = manual ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Capture it for same PI Payment should get succeeded with `status = succeeded` Again create a payment for capture = manual Void a Paymnet - Payment should get cancelled with `status = cancelled` 4. Create a O Auth mandate payment with stripe cards ``` { "amount": 0, "currency": "USD", "confirm": true, "setup_future_usage": "off_session", "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "payment_type": "setup_mandate", "payment_method": "card", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 7000, "currency": "USD" } } }, "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Chaser", "last_name": "Dough" }, "email": "example@juspay.in" } } ``` Response of 0 auth mandate ``` { "payment_id": "pay_L8pXs9YkASVJBvSSd0M2", "merchant_id": "postman_merchant_GHAction_5a2737e9-c107-411c-b458-8401b98e91ea", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "stripe", "client_secret": "pay_L8pXs9YkASVJBvSSd0M2_secret_oeTWqzB1O8kfVjzCeDDh", "created": "2024-03-19T06:56:47.885Z", "currency": "USD", "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "description": null, "refunds": null, "disputes": null, "mandate_id": "man_e0ADcjvb5OXgrGw1nF73", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 7000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Chaser", "last_name": "Dough" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "created_at": 1710831407, "expires": 1710835007, "secret": "epk_0ac0213b300e4d5f87c98645f96f5b6e" }, "manual_retry_allowed": false, "connector_transaction_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu", "payment_link": null, "profile_id": "pro_dHIsgCLvmZZcFRgkt3xE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mJiXEB1oLi5HXKhWCt9A", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-19T07:11:47.885Z", "fingerprint": null, "payment_method_id": "pm_SO8UJG7uDvc8oC2KgDAc", "payment_method_status": null } ``` Check the version after the payment in stripe dashboard. API-Version should be `"2022-11-15"`
[ "crates/router/src/connector/stripe/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4117
Bug: Add span metadata to `tokio` spawned futures Add span metadata to `tokio` spawned futures, as logs do not have parent span context.
diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs index c07b2112db2..b8d5743d8fe 100644 --- a/crates/common_utils/src/macros.rs +++ b/crates/common_utils/src/macros.rs @@ -47,13 +47,6 @@ macro_rules! newtype { }; } -#[macro_export] -macro_rules! async_spawn { - ($t:block) => { - tokio::spawn(async move { $t }); - }; -} - /// Use this to ensure that the corresponding /// openapi route has been implemented in the openapi crate #[macro_export] diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 44e4d174537..27bf11a7e6f 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -24,7 +24,6 @@ pub mod gsm; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; -pub mod macros; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; diff --git a/crates/diesel_models/src/macros.rs b/crates/diesel_models/src/macros.rs deleted file mode 100644 index de3596ecc10..00000000000 --- a/crates/diesel_models/src/macros.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[macro_export] -macro_rules! async_spawn { - ($t:block) => { - tokio::spawn(async move { $t }); - }; -} diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs index 5aa902d84c5..47b60db80d5 100644 --- a/crates/drainer/src/handler.rs +++ b/crates/drainer/src/handler.rs @@ -1,5 +1,6 @@ use std::sync::{atomic, Arc}; +use router_env::tracing::Instrument; use tokio::{ sync::{mpsc, oneshot}, time::{self, Duration}, @@ -68,13 +69,16 @@ impl Handler { while self.running.load(atomic::Ordering::SeqCst) { metrics::DRAINER_HEALTH.add(&metrics::CONTEXT, 1, &[]); if self.store.is_stream_available(stream_index).await { - tokio::spawn(drainer_handler( - self.store.clone(), - stream_index, - self.conf.max_read_count, - self.active_tasks.clone(), - jobs_picked.clone(), - )); + let _task_handle = tokio::spawn( + drainer_handler( + self.store.clone(), + stream_index, + self.conf.max_read_count, + self.active_tasks.clone(), + jobs_picked.clone(), + ) + .in_current_span(), + ); } stream_index = utils::increment_stream_index( (stream_index, jobs_picked.clone()), @@ -116,10 +120,12 @@ impl Handler { let redis_conn_clone = self.store.redis_conn.clone(); // Spawn a task to monitor if redis is down or not - tokio::spawn(async move { redis_conn_clone.on_error(redis_error_tx).await }); + let _task_handle = tokio::spawn( + async move { redis_conn_clone.on_error(redis_error_tx).await }.in_current_span(), + ); //Spawns a task to send shutdown signal if redis goes down - tokio::spawn(redis_error_receiver(redis_error_rx, tx)); + let _task_handle = tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span()); Ok(()) } diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 0ed6183faef..e7ae7621365 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -18,7 +18,10 @@ use common_utils::signals::get_allowed_signals; use diesel_models::kv; use error_stack::{IntoReport, ResultExt}; use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; -use router_env::{instrument, tracing}; +use router_env::{ + instrument, + tracing::{self, Instrument}, +}; use tokio::sync::mpsc; pub(crate) type Settings = crate::settings::Settings<RawSecret>; @@ -39,7 +42,8 @@ pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors:: "Failed while getting allowed signals".to_string(), ))?; let handle = signal.handle(); - let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone())); + let task_handle = + tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span()); let handler_clone = drainer_handler.clone(); diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index c586bfecdb7..1df37e9f6d1 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -16,7 +16,10 @@ use router::{ services::{self, api}, workflows, }; -use router_env::{instrument, tracing}; +use router_env::{ + instrument, + tracing::{self, Instrument}, +}; use scheduler::{ consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError, workflows::ProcessTrackerWorkflows, SchedulerAppState, @@ -49,10 +52,9 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { .await; // channel to shutdown scheduler gracefully let (tx, rx) = mpsc::channel(1); - tokio::spawn(router::receiver_for_error( - redis_shutdown_signal_rx, - tx.clone(), - )); + let _task_handle = tokio::spawn( + router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(), + ); #[allow(clippy::expect_used)] let scheduler_flow_str = @@ -81,10 +83,13 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { .await .expect("Failed to create the server"); - tokio::spawn(async move { - let _ = web_server.await; - logger::error!("The health check probe stopped working!"); - }); + let _task_handle = tokio::spawn( + async move { + let _ = web_server.await; + logger::error!("The health check probe stopped working!"); + } + .in_current_span(), + ); logger::debug!(startup_config=?state.conf); diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index efc0e8852da..7757313d867 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,5 +1,6 @@ use async_trait::async_trait; use error_stack; +use router_env::tracing::Instrument; use super::{ConstructFlowSpecificData, Feature}; use crate::{ @@ -125,26 +126,32 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu let state = state.clone(); logger::info!("Call to save_payment_method in locker"); - tokio::spawn(async move { - logger::info!("Starting async call to save_payment_method in locker"); - - let result = Box::pin(tokenization::save_payment_method( - &state, - &connector, - response, - &maybe_customer, - &merchant_account, - self.request.payment_method_type, - &key_store, - Some(resp.request.amount), - Some(resp.request.currency), - )) - .await; - - if let Err(err) = result { - logger::error!("Asynchronously saving card in locker failed : {:?}", err); + let _task_handle = tokio::spawn( + async move { + logger::info!("Starting async call to save_payment_method in locker"); + + let result = Box::pin(tokenization::save_payment_method( + &state, + &connector, + response, + &maybe_customer, + &merchant_account, + self.request.payment_method_type, + &key_store, + Some(resp.request.amount), + Some(resp.request.currency), + )) + .await; + + if let Err(err) = result { + logger::error!( + "Asynchronously saving card in locker failed : {:?}", + err + ); + } } - }); + .in_current_span(), + ); Ok(resp) } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 97b1d8e9817..b0bdc921107 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -160,18 +160,21 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let store = state.store.clone(); - let business_profile_fut = tokio::spawn(async move { - store - .find_business_profile_by_profile_id(&profile_id) - .map(|business_profile_result| { - business_profile_result.to_not_found_response( - errors::ApiErrorResponse::BusinessProfileNotFound { - id: profile_id.to_string(), - }, - ) - }) - .await - }); + let business_profile_fut = tokio::spawn( + async move { + store + .find_business_profile_by_profile_id(&profile_id) + .map(|business_profile_result| { + business_profile_result.to_not_found_response( + errors::ApiErrorResponse::BusinessProfileNotFound { + id: profile_id.to_string(), + }, + ) + }) + .await + } + .in_current_span(), + ); let store = state.store.clone(); @@ -498,13 +501,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let store = state.clone().store; - let additional_pm_data_fut = tokio::spawn(async move { - Ok(n_request_payment_method_data - .async_map(|payment_method_data| async move { - helpers::get_additional_payment_data(&payment_method_data, store.as_ref()).await - }) - .await) - }); + let additional_pm_data_fut = tokio::spawn( + async move { + Ok(n_request_payment_method_data + .async_map(|payment_method_data| async move { + helpers::get_additional_payment_data(&payment_method_data, store.as_ref()) + .await + }) + .await) + } + .in_current_span(), + ); let store = state.clone().store; diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 97d981c68eb..efba097d92d 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -31,6 +31,7 @@ use actix_web::{ }; use http::StatusCode; use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret; +use router_env::tracing::Instrument; use routes::AppState; use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; @@ -195,7 +196,7 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio .workers(server.workers) .shutdown_timeout(server.shutdown_timeout) .run(); - tokio::spawn(receiver_for_error(rx, server.handle())); + let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span()); Ok(server) } diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index e1ab3e80f32..5d48d6e8ad0 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -12,6 +12,7 @@ use actix_web::{ }; use derive_deref::Deref; use router::{configs::settings::Settings, routes::AppState, services}; +use router_env::tracing::Instrument; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::{json, Value}; use tokio::sync::{oneshot, OnceCell}; @@ -24,7 +25,7 @@ async fn spawn_server() -> bool { .await .expect("failed to create server"); - let _server = tokio::spawn(server); + let _server = tokio::spawn(server.in_current_span()); true } diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index e069db28da7..471f689ffc8 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -10,7 +10,10 @@ pub use diesel_models::{self, process_tracker as storage}; use error_stack::{IntoReport, ResultExt}; use futures::future; use redis_interface::{RedisConnectionPool, RedisEntryId}; -use router_env::{instrument, tracing}; +use router_env::{ + instrument, + tracing::{self, Instrument}, +}; use time::PrimitiveDateTime; use tokio::sync::mpsc; use uuid::Uuid; @@ -64,7 +67,8 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( .into_report() .attach_printable("Failed while creating a signals handler")?; let handle = signal.handle(); - let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx)); + let task_handle = + tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span()); 'consumer: loop { match rx.try_recv() { diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs index bcf37cdf6f2..b8081c2b9ae 100644 --- a/crates/scheduler/src/producer.rs +++ b/crates/scheduler/src/producer.rs @@ -3,7 +3,10 @@ use std::sync::Arc; use common_utils::errors::CustomResult; use diesel_models::enums::ProcessTrackerStatus; use error_stack::{report, IntoReport, ResultExt}; -use router_env::{instrument, tracing}; +use router_env::{ + instrument, + tracing::{self, Instrument}, +}; use time::Duration; use tokio::sync::mpsc; @@ -57,7 +60,8 @@ where .into_report() .attach_printable("Failed while creating a signals handler")?; let handle = signal.handle(); - let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx)); + let task_handle = + tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span()); loop { match rx.try_recv() { diff --git a/crates/storage_impl/src/redis.rs b/crates/storage_impl/src/redis.rs index e4e0c021ac8..be82d4cc293 100644 --- a/crates/storage_impl/src/redis.rs +++ b/crates/storage_impl/src/redis.rs @@ -6,7 +6,7 @@ use std::sync::{atomic, Arc}; use error_stack::{IntoReport, ResultExt}; use redis_interface::PubsubInterface; -use router_env::logger; +use router_env::{logger, tracing::Instrument}; use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface}; @@ -35,9 +35,12 @@ impl RedisStore { pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) { let redis_clone = self.redis_conn.clone(); - tokio::spawn(async move { - redis_clone.on_error(callback).await; - }); + let _task_handle = tokio::spawn( + async move { + redis_clone.on_error(callback).await; + } + .in_current_span(), + ); } pub async fn subscribe_to_channel( @@ -54,11 +57,14 @@ impl RedisStore { .change_context(redis_interface::errors::RedisError::SubscribeError)?; let redis_clone = self.redis_conn.clone(); - tokio::spawn(async move { - if let Err(e) = redis_clone.on_message().await { - logger::error!(pubsub_err=?e); + let _task_handle = tokio::spawn( + async move { + if let Err(e) = redis_clone.on_message().await { + logger::error!(pubsub_err=?e); + } } - }); + .in_current_span(), + ); Ok(()) } }
2024-03-18T14:41:37Z
## Description <!-- Describe your changes in detail --> Add span metadata to `tokio` spawned futures, as logs do not have parent span context. Also removed unused marco. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Logs of save payment method. Initially the `request_id` was not available for this logs. ![image](https://github.com/juspay/hyperswitch/assets/83439957/ce6f2d8a-de71-44cf-b4a2-67691288f5ab)
fcfd567bfe55747dcb05c88def96373a707f8c78
Logs of save payment method. Initially the `request_id` was not available for this logs. ![image](https://github.com/juspay/hyperswitch/assets/83439957/ce6f2d8a-de71-44cf-b4a2-67691288f5ab)
[ "crates/common_utils/src/macros.rs", "crates/diesel_models/src/lib.rs", "crates/diesel_models/src/macros.rs", "crates/drainer/src/handler.rs", "crates/drainer/src/lib.rs", "crates/router/src/bin/scheduler.rs", "crates/router/src/core/payments/flows/authorize_flow.rs", "crates/router/src/core/payments/...
juspay/hyperswitch
juspay__hyperswitch-3993
Bug: Route payments across `nrid_supported_connectors` if `pg_agnostic_mit` For the MITs check for the `pg_agnostic_mit` config flag, if it is `enabled` then apply the routing rule for the list of pg_agnostic connectors. In this case we need to apply the same routing rules which is configured for the other payments by applying the pg_agnostic connector filter.
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 45aeb1e9074..19a37ab0fb7 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -136,6 +136,7 @@ pub struct PaymentIntentRequest { #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, + #[serde(flatten)] pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated pub setup_future_usage: Option<enums::FutureUsage>, pub off_session: Option<bool>, @@ -189,9 +190,9 @@ pub struct StripeCardData { #[serde(rename = "payment_method_data[card][exp_year]")] pub payment_method_data_card_exp_year: Secret<String>, #[serde(rename = "payment_method_data[card][cvc]")] - pub payment_method_data_card_cvc: Secret<String>, + pub payment_method_data_card_cvc: Option<Secret<String>>, #[serde(rename = "payment_method_options[card][request_three_d_secure]")] - pub payment_method_auth_type: Auth3ds, + pub payment_method_auth_type: Option<Auth3ds>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePayLaterData { @@ -1498,8 +1499,8 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { payment_method_data_card_number: card.card_number.clone(), payment_method_data_card_exp_month: card.card_exp_month.clone(), payment_method_data_card_exp_year: card.card_exp_year.clone(), - payment_method_data_card_cvc: card.card_cvc.clone(), - payment_method_auth_type, + payment_method_data_card_cvc: Some(card.card_cvc.clone()), + payment_method_auth_type: Some(payment_method_auth_type), })) } } @@ -1821,7 +1822,44 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { network_transaction_id: Secret::new(network_transaction_id), }), }); - (None, None, StripeBillingAddress::default(), None) + + let payment_data = match item.request.payment_method_data { + domain::payments::PaymentMethodData::Card(ref card) => { + StripePaymentMethodData::Card(StripeCardData { + payment_method_data_type: StripePaymentMethodType::Card, + payment_method_data_card_number: card.card_number.clone(), + payment_method_data_card_exp_month: card.card_exp_month.clone(), + payment_method_data_card_exp_year: card.card_exp_year.clone(), + payment_method_data_card_cvc: None, + payment_method_auth_type: None, + }) + } + domain::payments::PaymentMethodData::CardRedirect(_) + | domain::payments::PaymentMethodData::Wallet(_) + | domain::payments::PaymentMethodData::PayLater(_) + | domain::payments::PaymentMethodData::BankRedirect(_) + | domain::payments::PaymentMethodData::BankDebit(_) + | domain::payments::PaymentMethodData::BankTransfer(_) + | domain::payments::PaymentMethodData::Crypto(_) + | domain::payments::PaymentMethodData::MandatePayment + | domain::payments::PaymentMethodData::Reward + | domain::payments::PaymentMethodData::Upi(_) + | domain::payments::PaymentMethodData::Voucher(_) + | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotSupported { + message: "Network tokenization for payment method".to_string(), + connector: "Stripe", + })? + } + }; + + ( + Some(payment_data), + None, + StripeBillingAddress::default(), + None, + ) } _ => { let (payment_method_data, payment_method_type, billing_address) = @@ -3105,10 +3143,13 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[non_exhaustive] #[serde(rename_all = "snake_case")] +#[serde(untagged)] pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, + #[serde(rename = "payment_method_options[card][network_transaction_id]")] network_transaction_id: Option<Secret<String>>, + #[serde(flatten)] mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, @@ -3139,6 +3180,7 @@ pub enum StripePaymentMethodOptions { #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct MitExemption { + #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")] pub network_transaction_id: Secret<String>, } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e7ec99f61b6..22f7cb311c6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2929,10 +2929,12 @@ where .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, payment_data, routing_data, connector_data, - ); + ) + .await; } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { @@ -2983,10 +2985,12 @@ where .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, payment_data, routing_data, connector_data, - ); + ) + .await; } route_connector_v1( @@ -3001,7 +3005,8 @@ where .await } -pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( +pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( + state: &AppState, payment_data: &mut PaymentData<F>, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, @@ -3010,9 +3015,11 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( payment_data.payment_intent.setup_future_usage, payment_data.token_data.as_ref(), payment_data.recurring_details.as_ref(), + payment_data.payment_intent.off_session, ) { - (Some(storage_enums::FutureUsage::OffSession), Some(_), None) - | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => { + (Some(storage_enums::FutureUsage::OffSession), Some(_), None, None) + | (None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true)) + | (None, Some(_), None, Some(true)) => { logger::debug!("performing routing for token-based MIT flow"); let payment_method_info = payment_data @@ -3020,32 +3027,108 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( .as_ref() .get_required_value("payment_method_info")?; - let connector_mandate_details = payment_method_info - .connector_mandate_details - .clone() - .map(|details| { - details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details") - }) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to deserialize connector mandate details")? - .get_required_value("connector_mandate_details") - .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?; + let connector_mandate_details = &payment_method_info + .connector_mandate_details + .clone() + .map(|details| { + details.parse_value::<storage::PaymentsMandateReference>( + "connector_mandate_details", + ) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize connector mandate details")?; + + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let pg_agnostic = state + .store + .find_config_by_key_unwrap_or( + &format!("pg_agnostic_mandate_{}", profile_id), + Some("false".to_string()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("The pg_agnostic config was not found in the DB")?; let mut connector_choice = None; + for connector_data in connectors { - if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { - if let Some(mandate_reference_record) = - connector_mandate_details.get(merchant_connector_id) + let merchant_connector_id = connector_data + .merchant_connector_id + .as_ref() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + if is_network_transaction_id_flow( + state, + &pg_agnostic.config, + connector_data.connector_name, + payment_method_info, + ) { + let network_transaction_id = payment_method_info + .network_transaction_id + .as_ref() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + let mandate_reference_id = + Some(payments_api::MandateReferenceId::NetworkMandateId( + network_transaction_id.to_string(), + )); + + connector_choice = Some((connector_data, mandate_reference_id.clone())); + break; + } else if connector_mandate_details + .clone() + .map(|connector_mandate_details| { + connector_mandate_details.contains_key(merchant_connector_id) + }) + .unwrap_or(false) + { + if let Some(merchant_connector_id) = + connector_data.merchant_connector_id.as_ref() { - connector_choice = Some((connector_data, mandate_reference_record.clone())); - break; + if let Some(mandate_reference_record) = connector_mandate_details.clone() + .get_required_value("connector_mandate_details") + .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")? + .get(merchant_connector_id) + { + let mandate_reference_id = + Some(payments_api::MandateReferenceId::ConnectorMandateId( + payments_api::ConnectorMandateReferenceId { + connector_mandate_id: Some( + mandate_reference_record.connector_mandate_id.clone(), + ), + payment_method_id: Some( + payment_method_info.payment_method_id.clone(), + ), + update_history: None, + }, + )); + payment_data.recurring_mandate_payment_data = + Some(RecurringMandatePaymentData { + payment_method_type: mandate_reference_record + .payment_method_type, + original_payment_authorized_amount: mandate_reference_record + .original_payment_authorized_amount, + original_payment_authorized_currency: mandate_reference_record + .original_payment_authorized_currency, + }); + + connector_choice = Some((connector_data, mandate_reference_id.clone())); + break; + } } + } else { + continue; } } - let (chosen_connector_data, mandate_reference_record) = connector_choice + let (chosen_connector_data, mandate_reference_id) = connector_choice .get_required_value("connector_choice") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT payment")?; @@ -3056,26 +3139,16 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( routing_data.merchant_connector_id = chosen_connector_data.merchant_connector_id.clone(); } + routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = + chosen_connector_data.merchant_connector_id.clone(); + } payment_data.mandate_id = Some(payments_api::MandateIds { mandate_id: None, - mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId( - payments_api::ConnectorMandateReferenceId { - connector_mandate_id: Some( - mandate_reference_record.connector_mandate_id.clone(), - ), - payment_method_id: Some(payment_method_info.payment_method_id.clone()), - update_history: None, - }, - )), - }); - - payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData { - payment_method_type: mandate_reference_record.payment_method_type, - original_payment_authorized_amount: mandate_reference_record - .original_payment_authorized_amount, - original_payment_authorized_currency: mandate_reference_record - .original_payment_authorized_currency, + mandate_reference_id, }); Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) @@ -3098,6 +3171,23 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( } } +pub fn is_network_transaction_id_flow( + state: &AppState, + pg_agnostic: &String, + connector: enums::Connector, + payment_method_info: &storage::PaymentMethod, +) -> bool { + let ntid_supported_connectors = &state + .conf + .network_transaction_id_supported_connectors + .connector_list; + + pg_agnostic == "true" + && payment_method_info.payment_method == storage_enums::PaymentMethod::Card + && ntid_supported_connectors.contains(&connector) + && payment_method_info.network_transaction_id.is_some() +} + pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool { let connector = payment_data.payment_attempt.connector.as_deref(); @@ -3315,10 +3405,12 @@ where match transaction_data { TransactionData::Payment(payment_data) => { decide_multiplex_connector_for_normal_or_recurring_payment( + state, payment_data, routing_data, connector_data, ) + .await } #[cfg(feature = "payouts")] diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 4eac9c1f4de..5214ce3f7a7 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -413,8 +413,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; - payment_attempt.payment_method_type = - payment_method_type.or(payment_attempt.payment_method_type); + payment_attempt.payment_method_type = payment_method_type + .or(payment_attempt.payment_method_type) + .or(payment_method_info + .as_ref() + .and_then(|pm_info| pm_info.payment_method_type)); payment_attempt.payment_experience = request .payment_experience diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index f418b660380..70cf702311d 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -972,18 +972,46 @@ async fn update_payment_method_status_and_ntid<F: Clone>( .find_payment_method(id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let network_transaction_id = payment_response - .map(|resp| match resp { - crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { - network_txn_id.to_owned() + + let pm_resp_network_transaction_id = payment_response + .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp { + network_transaction_id + } else {None}) + .map_err(|err| { + logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); + }) + .ok() + .flatten(); + + let network_transaction_id = + if let Some(network_transaction_id) = pm_resp_network_transaction_id { + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let pg_agnostic = state + .store + .find_config_by_key_unwrap_or( + &format!("pg_agnostic_mandate_{}", profile_id), + Some("false".to_string()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("The pg_agnostic config was not found in the DB")?; + + if &pg_agnostic.config == "true" { + Some(network_transaction_id) + } else { + logger::info!( + "Skip storing network transaction id as pg_agnostic config is not enabled" + ); + None } - _ => None, - }) - .map_err(|err| { - logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); - }) - .ok() - .flatten(); + } else { + None + }; let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active && pm.status != attempt_status.into()
2024-03-18T03:41:18Z
## Description <!-- Describe your changes in detail --> During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the pg_agnostic_mit config is enabled. If it is, perform a lookup in the payment methods table with the payment_method_id in the MIT payment request for the NRID. If the confirm call fails, retry across the retry-able connectors specified in the `pg_agnostic_mit` configuration. If the NRID is not present for that particular payment_method_id, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was performed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create a Merchant account Create a mca for stripe, adyen or cybersource Enable the pg_agnostic endpoint ``` curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ``` Create a mandate payment (Setup mandate) <img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92"> ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` DB screenshot where `network_transaction_id` is stored in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/f0dee8b8-193f-4013-9ebf-c749dc24643a) Create a payment with confirm false <img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468"> List payment methods for customer ``` curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` <img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293"> Confirm the payment by passing the connector as stripe in routing ``` { "amount": 300, "currency": "USD", "confirm": false, "customer_id": "cyb111", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } } ``` ``` curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "payment_token", "client_secret": "client_secret", "payment_method": "card" }' ``` <img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
63d2b6855acee1adeae2efff10f424e056af0bcb
Create a Merchant account Create a mca for stripe, adyen or cybersource Enable the pg_agnostic endpoint ``` curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ``` Create a mandate payment (Setup mandate) <img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92"> ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` DB screenshot where `network_transaction_id` is stored in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/f0dee8b8-193f-4013-9ebf-c749dc24643a) Create a payment with confirm false <img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468"> List payment methods for customer ``` curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` <img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293"> Confirm the payment by passing the connector as stripe in routing ``` { "amount": 300, "currency": "USD", "confirm": false, "customer_id": "cyb111", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } } ``` ``` curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "payment_token", "client_secret": "client_secret", "payment_method": "card" }' ``` <img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
[ "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/core/payments/operations/payment_response.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3994
Bug: Use NRID in recurring payments if the merchant config is enabled During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the `pg_agnostic_mit` config is enabled. If it is, perform a lookup in the payment methods table with the `payment_method_id` in the MIT payment request for the NRID. Retrieve the card details from the locker for the specific `payment_method_id`. Make the confirm call to the connector decided by routing. If the confirm call fails, retry across the retry-able connectors specified in the pg_agnostic_mit configuration. If the NRID is not present for that particular `payment_method_id`, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was performed.
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 45aeb1e9074..19a37ab0fb7 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -136,6 +136,7 @@ pub struct PaymentIntentRequest { #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, + #[serde(flatten)] pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated pub setup_future_usage: Option<enums::FutureUsage>, pub off_session: Option<bool>, @@ -189,9 +190,9 @@ pub struct StripeCardData { #[serde(rename = "payment_method_data[card][exp_year]")] pub payment_method_data_card_exp_year: Secret<String>, #[serde(rename = "payment_method_data[card][cvc]")] - pub payment_method_data_card_cvc: Secret<String>, + pub payment_method_data_card_cvc: Option<Secret<String>>, #[serde(rename = "payment_method_options[card][request_three_d_secure]")] - pub payment_method_auth_type: Auth3ds, + pub payment_method_auth_type: Option<Auth3ds>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePayLaterData { @@ -1498,8 +1499,8 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { payment_method_data_card_number: card.card_number.clone(), payment_method_data_card_exp_month: card.card_exp_month.clone(), payment_method_data_card_exp_year: card.card_exp_year.clone(), - payment_method_data_card_cvc: card.card_cvc.clone(), - payment_method_auth_type, + payment_method_data_card_cvc: Some(card.card_cvc.clone()), + payment_method_auth_type: Some(payment_method_auth_type), })) } } @@ -1821,7 +1822,44 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { network_transaction_id: Secret::new(network_transaction_id), }), }); - (None, None, StripeBillingAddress::default(), None) + + let payment_data = match item.request.payment_method_data { + domain::payments::PaymentMethodData::Card(ref card) => { + StripePaymentMethodData::Card(StripeCardData { + payment_method_data_type: StripePaymentMethodType::Card, + payment_method_data_card_number: card.card_number.clone(), + payment_method_data_card_exp_month: card.card_exp_month.clone(), + payment_method_data_card_exp_year: card.card_exp_year.clone(), + payment_method_data_card_cvc: None, + payment_method_auth_type: None, + }) + } + domain::payments::PaymentMethodData::CardRedirect(_) + | domain::payments::PaymentMethodData::Wallet(_) + | domain::payments::PaymentMethodData::PayLater(_) + | domain::payments::PaymentMethodData::BankRedirect(_) + | domain::payments::PaymentMethodData::BankDebit(_) + | domain::payments::PaymentMethodData::BankTransfer(_) + | domain::payments::PaymentMethodData::Crypto(_) + | domain::payments::PaymentMethodData::MandatePayment + | domain::payments::PaymentMethodData::Reward + | domain::payments::PaymentMethodData::Upi(_) + | domain::payments::PaymentMethodData::Voucher(_) + | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotSupported { + message: "Network tokenization for payment method".to_string(), + connector: "Stripe", + })? + } + }; + + ( + Some(payment_data), + None, + StripeBillingAddress::default(), + None, + ) } _ => { let (payment_method_data, payment_method_type, billing_address) = @@ -3105,10 +3143,13 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[non_exhaustive] #[serde(rename_all = "snake_case")] +#[serde(untagged)] pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, + #[serde(rename = "payment_method_options[card][network_transaction_id]")] network_transaction_id: Option<Secret<String>>, + #[serde(flatten)] mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, @@ -3139,6 +3180,7 @@ pub enum StripePaymentMethodOptions { #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct MitExemption { + #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")] pub network_transaction_id: Secret<String>, } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e7ec99f61b6..22f7cb311c6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2929,10 +2929,12 @@ where .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, payment_data, routing_data, connector_data, - ); + ) + .await; } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { @@ -2983,10 +2985,12 @@ where .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, payment_data, routing_data, connector_data, - ); + ) + .await; } route_connector_v1( @@ -3001,7 +3005,8 @@ where .await } -pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( +pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( + state: &AppState, payment_data: &mut PaymentData<F>, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, @@ -3010,9 +3015,11 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( payment_data.payment_intent.setup_future_usage, payment_data.token_data.as_ref(), payment_data.recurring_details.as_ref(), + payment_data.payment_intent.off_session, ) { - (Some(storage_enums::FutureUsage::OffSession), Some(_), None) - | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => { + (Some(storage_enums::FutureUsage::OffSession), Some(_), None, None) + | (None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true)) + | (None, Some(_), None, Some(true)) => { logger::debug!("performing routing for token-based MIT flow"); let payment_method_info = payment_data @@ -3020,32 +3027,108 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( .as_ref() .get_required_value("payment_method_info")?; - let connector_mandate_details = payment_method_info - .connector_mandate_details - .clone() - .map(|details| { - details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details") - }) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to deserialize connector mandate details")? - .get_required_value("connector_mandate_details") - .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?; + let connector_mandate_details = &payment_method_info + .connector_mandate_details + .clone() + .map(|details| { + details.parse_value::<storage::PaymentsMandateReference>( + "connector_mandate_details", + ) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize connector mandate details")?; + + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let pg_agnostic = state + .store + .find_config_by_key_unwrap_or( + &format!("pg_agnostic_mandate_{}", profile_id), + Some("false".to_string()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("The pg_agnostic config was not found in the DB")?; let mut connector_choice = None; + for connector_data in connectors { - if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { - if let Some(mandate_reference_record) = - connector_mandate_details.get(merchant_connector_id) + let merchant_connector_id = connector_data + .merchant_connector_id + .as_ref() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + if is_network_transaction_id_flow( + state, + &pg_agnostic.config, + connector_data.connector_name, + payment_method_info, + ) { + let network_transaction_id = payment_method_info + .network_transaction_id + .as_ref() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + let mandate_reference_id = + Some(payments_api::MandateReferenceId::NetworkMandateId( + network_transaction_id.to_string(), + )); + + connector_choice = Some((connector_data, mandate_reference_id.clone())); + break; + } else if connector_mandate_details + .clone() + .map(|connector_mandate_details| { + connector_mandate_details.contains_key(merchant_connector_id) + }) + .unwrap_or(false) + { + if let Some(merchant_connector_id) = + connector_data.merchant_connector_id.as_ref() { - connector_choice = Some((connector_data, mandate_reference_record.clone())); - break; + if let Some(mandate_reference_record) = connector_mandate_details.clone() + .get_required_value("connector_mandate_details") + .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")? + .get(merchant_connector_id) + { + let mandate_reference_id = + Some(payments_api::MandateReferenceId::ConnectorMandateId( + payments_api::ConnectorMandateReferenceId { + connector_mandate_id: Some( + mandate_reference_record.connector_mandate_id.clone(), + ), + payment_method_id: Some( + payment_method_info.payment_method_id.clone(), + ), + update_history: None, + }, + )); + payment_data.recurring_mandate_payment_data = + Some(RecurringMandatePaymentData { + payment_method_type: mandate_reference_record + .payment_method_type, + original_payment_authorized_amount: mandate_reference_record + .original_payment_authorized_amount, + original_payment_authorized_currency: mandate_reference_record + .original_payment_authorized_currency, + }); + + connector_choice = Some((connector_data, mandate_reference_id.clone())); + break; + } } + } else { + continue; } } - let (chosen_connector_data, mandate_reference_record) = connector_choice + let (chosen_connector_data, mandate_reference_id) = connector_choice .get_required_value("connector_choice") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT payment")?; @@ -3056,26 +3139,16 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( routing_data.merchant_connector_id = chosen_connector_data.merchant_connector_id.clone(); } + routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = + chosen_connector_data.merchant_connector_id.clone(); + } payment_data.mandate_id = Some(payments_api::MandateIds { mandate_id: None, - mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId( - payments_api::ConnectorMandateReferenceId { - connector_mandate_id: Some( - mandate_reference_record.connector_mandate_id.clone(), - ), - payment_method_id: Some(payment_method_info.payment_method_id.clone()), - update_history: None, - }, - )), - }); - - payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData { - payment_method_type: mandate_reference_record.payment_method_type, - original_payment_authorized_amount: mandate_reference_record - .original_payment_authorized_amount, - original_payment_authorized_currency: mandate_reference_record - .original_payment_authorized_currency, + mandate_reference_id, }); Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) @@ -3098,6 +3171,23 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( } } +pub fn is_network_transaction_id_flow( + state: &AppState, + pg_agnostic: &String, + connector: enums::Connector, + payment_method_info: &storage::PaymentMethod, +) -> bool { + let ntid_supported_connectors = &state + .conf + .network_transaction_id_supported_connectors + .connector_list; + + pg_agnostic == "true" + && payment_method_info.payment_method == storage_enums::PaymentMethod::Card + && ntid_supported_connectors.contains(&connector) + && payment_method_info.network_transaction_id.is_some() +} + pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool { let connector = payment_data.payment_attempt.connector.as_deref(); @@ -3315,10 +3405,12 @@ where match transaction_data { TransactionData::Payment(payment_data) => { decide_multiplex_connector_for_normal_or_recurring_payment( + state, payment_data, routing_data, connector_data, ) + .await } #[cfg(feature = "payouts")] diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 4eac9c1f4de..5214ce3f7a7 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -413,8 +413,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; - payment_attempt.payment_method_type = - payment_method_type.or(payment_attempt.payment_method_type); + payment_attempt.payment_method_type = payment_method_type + .or(payment_attempt.payment_method_type) + .or(payment_method_info + .as_ref() + .and_then(|pm_info| pm_info.payment_method_type)); payment_attempt.payment_experience = request .payment_experience diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index f418b660380..70cf702311d 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -972,18 +972,46 @@ async fn update_payment_method_status_and_ntid<F: Clone>( .find_payment_method(id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let network_transaction_id = payment_response - .map(|resp| match resp { - crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { - network_txn_id.to_owned() + + let pm_resp_network_transaction_id = payment_response + .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp { + network_transaction_id + } else {None}) + .map_err(|err| { + logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); + }) + .ok() + .flatten(); + + let network_transaction_id = + if let Some(network_transaction_id) = pm_resp_network_transaction_id { + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let pg_agnostic = state + .store + .find_config_by_key_unwrap_or( + &format!("pg_agnostic_mandate_{}", profile_id), + Some("false".to_string()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("The pg_agnostic config was not found in the DB")?; + + if &pg_agnostic.config == "true" { + Some(network_transaction_id) + } else { + logger::info!( + "Skip storing network transaction id as pg_agnostic config is not enabled" + ); + None } - _ => None, - }) - .map_err(|err| { - logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); - }) - .ok() - .flatten(); + } else { + None + }; let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active && pm.status != attempt_status.into()
2024-03-18T03:41:18Z
## Description <!-- Describe your changes in detail --> During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the pg_agnostic_mit config is enabled. If it is, perform a lookup in the payment methods table with the payment_method_id in the MIT payment request for the NRID. If the confirm call fails, retry across the retry-able connectors specified in the `pg_agnostic_mit` configuration. If the NRID is not present for that particular payment_method_id, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was performed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create a Merchant account Create a mca for stripe, adyen or cybersource Enable the pg_agnostic endpoint ``` curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ``` Create a mandate payment (Setup mandate) <img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92"> ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` DB screenshot where `network_transaction_id` is stored in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/f0dee8b8-193f-4013-9ebf-c749dc24643a) Create a payment with confirm false <img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468"> List payment methods for customer ``` curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` <img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293"> Confirm the payment by passing the connector as stripe in routing ``` { "amount": 300, "currency": "USD", "confirm": false, "customer_id": "cyb111", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } } ``` ``` curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "payment_token", "client_secret": "client_secret", "payment_method": "card" }' ``` <img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
63d2b6855acee1adeae2efff10f424e056af0bcb
Create a Merchant account Create a mca for stripe, adyen or cybersource Enable the pg_agnostic endpoint ``` curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ``` Create a mandate payment (Setup mandate) <img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92"> ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` DB screenshot where `network_transaction_id` is stored in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/f0dee8b8-193f-4013-9ebf-c749dc24643a) Create a payment with confirm false <img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468"> List payment methods for customer ``` curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` <img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293"> Confirm the payment by passing the connector as stripe in routing ``` { "amount": 300, "currency": "USD", "confirm": false, "customer_id": "cyb111", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } } ``` ``` curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "payment_token", "client_secret": "client_secret", "payment_method": "card" }' ``` <img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
[ "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/core/payments/operations/payment_response.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4112
Bug: [BUG] : [Stripe] make name mandatory ### Bug Description Field called name in stripe Shipping address is not an optional at the stripe's end but it is optional in hyperswitch's stripe transformer ### Expected Behavior Stripe transformer must treat name as a mandatory field ### Actual Behavior Stripe transformer treats name as an optional field ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 45e2c795a0d..82dee21f7e6 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -117,7 +117,7 @@ pub struct PaymentIntentRequest { pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, #[serde(flatten)] - pub shipping: StripeShippingAddress, + pub shipping: Option<StripeShippingAddress>, #[serde(flatten)] pub billing: StripeBillingAddress, #[serde(flatten)] @@ -882,26 +882,33 @@ impl TryFrom<&api_models::enums::BankNames> for StripeBankNames { } fn validate_shipping_address_against_payment_method( - shipping_address: &StripeShippingAddress, + shipping_address: &Option<StripeShippingAddress>, payment_method: Option<&StripePaymentMethodType>, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { - if let Some(StripePaymentMethodType::AfterpayClearpay) = payment_method { - let missing_fields = collect_missing_value_keys!( - ("shipping.address.first_name", shipping_address.name), - ("shipping.address.line1", shipping_address.line1), - ("shipping.address.country", shipping_address.country), - ("shipping.address.zip", shipping_address.zip) - ); - - if !missing_fields.is_empty() { - return Err(errors::ConnectorError::MissingRequiredFields { - field_names: missing_fields, + match payment_method { + Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address { + Some(address) => { + let missing_fields = collect_missing_value_keys!( + ("shipping.address.line1", address.line1), + ("shipping.address.country", address.country), + ("shipping.address.zip", address.zip) + ); + + if !missing_fields.is_empty() { + return Err(errors::ConnectorError::MissingRequiredFields { + field_names: missing_fields, + }) + .into_report(); + } + Ok(()) + } + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "shipping.address", }) - .into_report(); - } + .into_report(), + }, + _ => Ok(()), } - - Ok(()) } impl TryFrom<&api_models::payments::PayLaterData> for StripePaymentMethodType { @@ -1717,23 +1724,27 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { let shipping_address = match item.get_optional_shipping() { Some(shipping_details) => { let shipping_address = shipping_details.address.as_ref(); - StripeShippingAddress { + Some(StripeShippingAddress { city: shipping_address.and_then(|a| a.city.clone()), country: shipping_address.and_then(|a| a.country), line1: shipping_address.and_then(|a| a.line1.clone()), line2: shipping_address.and_then(|a| a.line2.clone()), zip: shipping_address.and_then(|a| a.zip.clone()), state: shipping_address.and_then(|a| a.state.clone()), - name: shipping_address.and_then(|a| { - a.first_name.as_ref().map(|first_name| { - format!( - "{} {}", - first_name.clone().expose(), - a.last_name.clone().expose_option().unwrap_or_default() - ) - .into() + name: shipping_address + .and_then(|a| { + a.first_name.as_ref().map(|first_name| { + format!( + "{} {}", + first_name.clone().expose(), + a.last_name.clone().expose_option().unwrap_or_default() + ) + .into() + }) }) - }), + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "shipping_address.first_name", + })?, phone: shipping_details.phone.as_ref().map(|p| { format!( "{}{}", @@ -1742,9 +1753,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { ) .into() }), - } + }) } - None => StripeShippingAddress::default(), + None => None, }; let billing_address = match item.get_optional_billing() { @@ -2930,7 +2941,7 @@ pub struct StripeShippingAddress { #[serde(rename = "shipping[address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "shipping[name]")] - pub name: Option<Secret<String>>, + pub name: Secret<String>, #[serde(rename = "shipping[phone]")] pub phone: Option<Secret<String>>, } @@ -3841,7 +3852,7 @@ mod test_validate_shipping_address_against_payment_method { fn should_return_ok() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( - Some("name".to_string()), + "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), Some("zip".to_string()), @@ -3851,7 +3862,7 @@ mod test_validate_shipping_address_against_payment_method { //Act let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, + &Some(stripe_shipping_address), Some(payment_method), ); @@ -3859,39 +3870,11 @@ mod test_validate_shipping_address_against_payment_method { assert!(result.is_ok()); } - #[test] - fn should_return_err_for_empty_name() { - // Arrange - let stripe_shipping_address = create_stripe_shipping_address( - None, - Some("line1".to_string()), - Some(CountryAlpha2::AD), - Some("zip".to_string()), - ); - - let payment_method = &StripePaymentMethodType::AfterpayClearpay; - - //Act - let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, - Some(payment_method), - ); - - // Assert - assert!(result.is_err()); - let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); - assert_eq!(missing_fields.len(), 1); - assert_eq!( - *missing_fields.first().unwrap(), - "shipping.address.first_name" - ); - } - #[test] fn should_return_err_for_empty_line1() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( - Some("name".to_string()), + "name".to_string(), None, Some(CountryAlpha2::AD), Some("zip".to_string()), @@ -3901,7 +3884,7 @@ mod test_validate_shipping_address_against_payment_method { //Act let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, + &Some(stripe_shipping_address), Some(payment_method), ); @@ -3916,7 +3899,7 @@ mod test_validate_shipping_address_against_payment_method { fn should_return_err_for_empty_country() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( - Some("name".to_string()), + "name".to_string(), Some("line1".to_string()), None, Some("zip".to_string()), @@ -3926,7 +3909,7 @@ mod test_validate_shipping_address_against_payment_method { //Act let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, + &Some(stripe_shipping_address), Some(payment_method), ); @@ -3941,7 +3924,7 @@ mod test_validate_shipping_address_against_payment_method { fn should_return_err_for_empty_zip() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( - Some("name".to_string()), + "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), None, @@ -3950,7 +3933,7 @@ mod test_validate_shipping_address_against_payment_method { //Act let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, + &Some(stripe_shipping_address), Some(payment_method), ); @@ -3967,7 +3950,7 @@ mod test_validate_shipping_address_against_payment_method { let expected_missing_field_names: Vec<&'static str> = vec!["shipping.address.zip", "shipping.address.country"]; let stripe_shipping_address = create_stripe_shipping_address( - Some("name".to_string()), + "name".to_string(), Some("line1".to_string()), None, None, @@ -3976,7 +3959,7 @@ mod test_validate_shipping_address_against_payment_method { //Act let result = validate_shipping_address_against_payment_method( - &stripe_shipping_address, + &Some(stripe_shipping_address), Some(payment_method), ); @@ -3997,13 +3980,13 @@ mod test_validate_shipping_address_against_payment_method { } fn create_stripe_shipping_address( - name: Option<String>, + name: String, line1: Option<String>, country: Option<CountryAlpha2>, zip: Option<String>, ) -> StripeShippingAddress { StripeShippingAddress { - name: name.map(Secret::new), + name: Secret::new(name), line1: line1.map(Secret::new), country, zip: zip.map(Secret::new),
2024-03-15T10:41:12Z
## Description <!-- Describe your changes in detail --> Field called `name` in stripe Shipping address is not optional at the stripe's end. This PR makes it a mandatory field. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{}}' \ --data-raw '{ "amount": 7000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "SE" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "order_details": { "product_name": "Socks", "amount": 7000, "quantity": 1 } }, "payment_method": "pay_later", "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "payment_method_data": { "pay_later": { "afterpay_clearpay_redirect": { "billing_name": "Akshaya", "billing_email": "example@example.com" } } } }' ``` Response ``` { "error": { "type": "invalid_request", "message": "Missing required param: shipping_address.first_name", "code": "IR_04" } } ```
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
[ "crates/router/src/connector/stripe/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4090
Bug: [BUG]: Stripe API version should be passed in the API headers ### Bug Description Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. This can be avoided by passing version which was implemented at Hyperswitch in the headers while calling Stripe API's. For more info - https://docs.stripe.com/api/versioning ### Expected Behavior Stripe Merchant account with any API version as default should be able to use Stripe integration with Hyperswitch ### Actual Behavior Deserialization error ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 7718c2fc729..958867465f9 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -7,6 +7,7 @@ use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; use masking::PeekInterface; use router_env::{instrument, tracing}; +use stripe::auth_headers; use self::transformers as stripe; use super::utils::{self as connector_utils, RefundsRequestData}; @@ -55,10 +56,16 @@ impl ConnectorCommon for Stripe { let auth: stripe::StripeAuthType = auth_type .try_into() .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key.peek()).into_masked(), - )]) + Ok(vec![ + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", auth.api_key.peek()).into_masked(), + ), + ( + auth_headers::STRIPE_API_VERSION.to_string(), + auth_headers::STRIPE_VERSION.to_string().into_masked(), + ), + ]) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 45e2c795a0d..719710b602b 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -32,6 +32,11 @@ use crate::{ utils::OptionExt, }; +pub mod auth_headers { + pub const STRIPE_API_VERSION: &str = "stripe-version"; + pub const STRIPE_VERSION: &str = "2023-10-16"; +} + pub struct StripeAuthType { pub(super) api_key: Secret<String>, }
2024-03-15T10:16:44Z
## Description Fixes https://github.com/juspay/hyperswitch/issues/4090 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Create a stripe Card Payment Request ``` { "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Response ``` { "payment_id": "pay_cmmd8900wIRqd11y6kUL", "merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL", "created": "2024-03-15T10:59:51.115Z", "currency": "INR", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710500391, "expires": 1710503991, "secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "payment_link": null, "profile_id": "pro_2x6hcEAjCQmaYxIpxO5V", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:14:51.115Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id` For that payment check the header-info , API-Version should be `"2023-10-16"`
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
Create a stripe Card Payment Request ``` { "amount": 6540, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` Response ``` { "payment_id": "pay_cmmd8900wIRqd11y6kUL", "merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL", "created": "2024-03-15T10:59:51.115Z", "currency": "INR", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710500391, "expires": 1710503991, "secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuYUND5R7gDAGff1bwg1RSP", "payment_link": null, "profile_id": "pro_2x6hcEAjCQmaYxIpxO5V", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:14:51.115Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id` For that payment check the header-info , API-Version should be `"2023-10-16"`
[ "crates/router/src/connector/stripe.rs", "crates/router/src/connector/stripe/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4106
Bug: [FEATURE] [CYBERSOURCE/BOA] Add support for payment status ACCEPTED and CANCELLED ### Feature Description The payment response must address the `ACCEPTED` and `CANCELLED` payment status from connectors Bankofamerica and Cybersource. ### Possible Implementation Payment status `ACCEPTED` and `CANCELLED` should be added to `CybersourcePaymentStatus` and `BankofamericaPaymentStatus` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 8e30e2b0475..b9a14321025 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -896,6 +896,8 @@ pub enum BankofamericaPaymentStatus { ServerError, PendingAuthentication, PendingReview, + Accepted, + Cancelled, //PartialAuthorized, not being consumed yet. } @@ -921,9 +923,9 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => { Self::Charged } - BankofamericaPaymentStatus::Voided | BankofamericaPaymentStatus::Reversed => { - Self::Voided - } + BankofamericaPaymentStatus::Voided + | BankofamericaPaymentStatus::Reversed + | BankofamericaPaymentStatus::Cancelled => Self::Voided, BankofamericaPaymentStatus::Failed | BankofamericaPaymentStatus::Declined | BankofamericaPaymentStatus::AuthorizedRiskDeclined @@ -931,9 +933,9 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { | BankofamericaPaymentStatus::Rejected | BankofamericaPaymentStatus::ServerError => Self::Failure, BankofamericaPaymentStatus::PendingAuthentication => Self::AuthenticationPending, - BankofamericaPaymentStatus::PendingReview | BankofamericaPaymentStatus::Challenge => { - Self::Pending - } + BankofamericaPaymentStatus::PendingReview + | BankofamericaPaymentStatus::Challenge + | BankofamericaPaymentStatus::Accepted => Self::Pending, } } } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index fb80c0a1c48..d9fab9a9025 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1397,6 +1397,8 @@ pub enum CybersourcePaymentStatus { ServerError, PendingAuthentication, PendingReview, + Accepted, + Cancelled, //PartialAuthorized, not being consumed yet. } @@ -1430,7 +1432,9 @@ impl ForeignFrom<(CybersourcePaymentStatus, bool)> for enums::AttemptStatus { CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => { Self::Charged } - CybersourcePaymentStatus::Voided | CybersourcePaymentStatus::Reversed => Self::Voided, + CybersourcePaymentStatus::Voided + | CybersourcePaymentStatus::Reversed + | CybersourcePaymentStatus::Cancelled => Self::Voided, CybersourcePaymentStatus::Failed | CybersourcePaymentStatus::Declined | CybersourcePaymentStatus::AuthorizedRiskDeclined @@ -1438,9 +1442,9 @@ impl ForeignFrom<(CybersourcePaymentStatus, bool)> for enums::AttemptStatus { | CybersourcePaymentStatus::InvalidRequest | CybersourcePaymentStatus::ServerError => Self::Failure, CybersourcePaymentStatus::PendingAuthentication => Self::AuthenticationPending, - CybersourcePaymentStatus::PendingReview | CybersourcePaymentStatus::Challenge => { - Self::Pending - } + CybersourcePaymentStatus::PendingReview + | CybersourcePaymentStatus::Challenge + | CybersourcePaymentStatus::Accepted => Self::Pending, } } }
2024-03-15T10:03:52Z
## Description <!-- Describe your changes in detail --> The payment response will also address the `ACCEPTED` and `CANCELLED` payment status from connectors Bankofamerica and Cybersource. ![Screenshot 2024-03-15 at 6 52 36 PM](https://github.com/juspay/hyperswitch/assets/41580413/e1ba2ec2-9ebb-43da-8afe-f20f06ddf6eb) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4106 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing can be done by creating a recurring payment of 2USD using a Zero Auth Mandate in Cybersource. 1. Payments Intent Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "order_details": null, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "cut2", "email": "johndoe@gmail.com", "description": "Hello this is description", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "metadata": {}, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_4ajjiLQoHDyuxTvmS6cT", "merchant_id": "merchant_1709635075", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id", "created": "2024-03-15T10:08:50.893Z", "currency": "USD", "customer_id": "cut2", "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cut2", "created_at": 1710497330, "expires": 1710500930, "secret": "epk_1d6c5154433d4a3b8a3931b4f53591b8" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:23:50.892Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payments Confirm: Request: ``` curl --location 'http://localhost:8080/payments/pay_4ajjiLQoHDyuxTvmS6cT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "off_session": true, "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 68607706, "currency": "USD" } } } }' ``` Response: ``` { "payment_id": "pay_4ajjiLQoHDyuxTvmS6cT", "merchant_id": "merchant_1709635075", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id", "created": "2024-03-15T10:08:50.893Z", "currency": "USD", "customer_id": "cut2", "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": "token_flejprZEsxCiCGI8CP4a", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7104973647776605504951", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4ajjiLQoHDyuxTvmS6cT_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:23:50.892Z", "fingerprint": null, "payment_method_id": "pm_PmD3Qlt1WtgPbdbC16ZG", "payment_method_status": null } ``` 3. Payments Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": true, "customer_id": "cut2", "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "capture_method": "automatic", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "off_session":true, "browser_info": { "ip_address":"172.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } } }' ``` Response: ``` { "payment_id": "pay_M2pKqiENVxQNMxJyOxXW", "merchant_id": "merchant_1709635075", "status": "processing", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_M2pKqiENVxQNMxJyOxXW_secret_zx26uFNfobl0m2iKU8UM", "created": "2024-03-15T10:32:24.673Z", "currency": "USD", "customer_id": "cut2", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": null, "payment_token": "d1e9248c-579f-4322-ad12-24ba69206d24", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cut2", "created_at": 1710498744, "expires": 1710502344, "secret": "epk_9aab59452e7545c9a4cded4951ac4c51" }, "manual_retry_allowed": false, "connector_transaction_id": "7104987458396042804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_M2pKqiENVxQNMxJyOxXW_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:47:24.672Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` NOTE: The status should be `processing` in the above payments response. 4. Payments - Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_M2pKqiENVxQNMxJyOxXW?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' ``` Response: ``` { "payment_id": "pay_wTenpwi3b9XkyvTqyRee", "merchant_id": "merchant_1709635075", "status": "cancelled", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_wTenpwi3b9XkyvTqyRee_secret_IOIapF3mBQVf2Vj2OSan", "created": "2024-03-15T10:48:51.707Z", "currency": "USD", "customer_id": "cut2", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": null, "payment_token": "d2d40950-39be-47d7-9741-f93e2cb89afa", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7104997332846410804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_wTenpwi3b9XkyvTqyRee_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:03:51.707Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` NOTE: The status should be `cancelled` in the above payments retrieve response.
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
Testing can be done by creating a recurring payment of 2USD using a Zero Auth Mandate in Cybersource. 1. Payments Intent Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "order_details": null, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "cut2", "email": "johndoe@gmail.com", "description": "Hello this is description", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "metadata": {}, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_4ajjiLQoHDyuxTvmS6cT", "merchant_id": "merchant_1709635075", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id", "created": "2024-03-15T10:08:50.893Z", "currency": "USD", "customer_id": "cut2", "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cut2", "created_at": 1710497330, "expires": 1710500930, "secret": "epk_1d6c5154433d4a3b8a3931b4f53591b8" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:23:50.892Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payments Confirm: Request: ``` curl --location 'http://localhost:8080/payments/pay_4ajjiLQoHDyuxTvmS6cT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "off_session": true, "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 68607706, "currency": "USD" } } } }' ``` Response: ``` { "payment_id": "pay_4ajjiLQoHDyuxTvmS6cT", "merchant_id": "merchant_1709635075", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id", "created": "2024-03-15T10:08:50.893Z", "currency": "USD", "customer_id": "cut2", "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": "token_flejprZEsxCiCGI8CP4a", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7104973647776605504951", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4ajjiLQoHDyuxTvmS6cT_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:23:50.892Z", "fingerprint": null, "payment_method_id": "pm_PmD3Qlt1WtgPbdbC16ZG", "payment_method_status": null } ``` 3. Payments Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": true, "customer_id": "cut2", "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "capture_method": "automatic", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "off_session":true, "browser_info": { "ip_address":"172.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } } }' ``` Response: ``` { "payment_id": "pay_M2pKqiENVxQNMxJyOxXW", "merchant_id": "merchant_1709635075", "status": "processing", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_M2pKqiENVxQNMxJyOxXW_secret_zx26uFNfobl0m2iKU8UM", "created": "2024-03-15T10:32:24.673Z", "currency": "USD", "customer_id": "cut2", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": null, "payment_token": "d1e9248c-579f-4322-ad12-24ba69206d24", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cut2", "created_at": 1710498744, "expires": 1710502344, "secret": "epk_9aab59452e7545c9a4cded4951ac4c51" }, "manual_retry_allowed": false, "connector_transaction_id": "7104987458396042804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_M2pKqiENVxQNMxJyOxXW_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T10:47:24.672Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` NOTE: The status should be `processing` in the above payments response. 4. Payments - Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_M2pKqiENVxQNMxJyOxXW?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' ``` Response: ``` { "payment_id": "pay_wTenpwi3b9XkyvTqyRee", "merchant_id": "merchant_1709635075", "status": "cancelled", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_wTenpwi3b9XkyvTqyRee_secret_IOIapF3mBQVf2Vj2OSan", "created": "2024-03-15T10:48:51.707Z", "currency": "USD", "customer_id": "cut2", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_i7TaAdtRTW1qruRs87Xa", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": null, "payment_token": "d2d40950-39be-47d7-9741-f93e2cb89afa", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7104997332846410804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_wTenpwi3b9XkyvTqyRee_1", "payment_link": null, "profile_id": "pro_dMJfhV51DYUbzCBKrQDw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T11:03:51.707Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` NOTE: The status should be `cancelled` in the above payments retrieve response.
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4103
Bug: fix: populate merchant connector id and profile id in payments list Currently in payments list response, merchant connector id and profile id is not getting populated for payments list response, though the value is present in db.
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 315ddd3b39b..313d520fdac 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -952,6 +952,8 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay authentication_type: pa.authentication_type, connector_transaction_id: pa.connector_transaction_id, attempt_count: pi.attempt_count, + profile_id: pi.profile_id, + merchant_connector_id: pa.merchant_connector_id, ..Default::default() } }
2024-03-15T09:14:10Z
## Description `Profile_id` and `merchant_connector_id` is to be populated for payments list response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context closes #4103 ## How did you test it? Use the curl to get payments list: ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` In Response fields `profile_id` and `merchant_connector_id` fields properly populated. ``` { "count": 5, "total_count": 100, "data": [ { "payment_id": "test_fhYXl6ExKokyMqAlnDiz", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 16700, "net_amount": 0, "amount_capturable": 16700, "amount_received": null, "connector": "stripe_test", "client_secret": "test_fhYXl6ExKokyMqAlnDiz_secret_0Lfp0rpudua13MFoT8NU", "created": "2024-03-14T08:10:15.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_fhYXl6ExKokyMqAlnDiz_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_ejaOwTOxyNQu5WrDeZnk", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 14600, "net_amount": 0, "amount_capturable": 14600, "amount_received": null, "connector": "paypal_test", "client_secret": "test_ejaOwTOxyNQu5WrDeZnk_secret_l6jUZkSzjkNpa8xnzwwj", "created": "2024-03-14T05:25:35.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_ejaOwTOxyNQu5WrDeZnk_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_MB9kqEtqMONlQEPHb1dT", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 12900, "net_amount": 0, "amount_capturable": 12900, "amount_received": null, "connector": "stripe_test", "client_secret": "test_MB9kqEtqMONlQEPHb1dT_secret_kSeuhHJkrZcBndgMWRP2", "created": "2024-03-14T05:02:09.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_MB9kqEtqMONlQEPHb1dT_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_kWl22oD2BdhPq3LM260p", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 11100, "net_amount": 0, "amount_capturable": 11100, "amount_received": null, "connector": "paypal_test", "client_secret": "test_kWl22oD2BdhPq3LM260p_secret_1KRPGPVx25PyjGcowDti", "created": "2024-03-14T04:27:59.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_kWl22oD2BdhPq3LM260p_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_uNRkJ3WbgCmZr7CF58Ev", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 12900, "net_amount": 0, "amount_capturable": 12900, "amount_received": null, "connector": "stripe_test", "client_secret": "test_uNRkJ3WbgCmZr7CF58Ev_secret_yzc8nAG4qTdQVpSjmnwP", "created": "2024-03-14T03:43:12.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_uNRkJ3WbgCmZr7CF58Ev_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ] } ```
f9db641058179b846d4bf3ce69a7679b4e9541fc
Use the curl to get payments list: ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` In Response fields `profile_id` and `merchant_connector_id` fields properly populated. ``` { "count": 5, "total_count": 100, "data": [ { "payment_id": "test_fhYXl6ExKokyMqAlnDiz", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 16700, "net_amount": 0, "amount_capturable": 16700, "amount_received": null, "connector": "stripe_test", "client_secret": "test_fhYXl6ExKokyMqAlnDiz_secret_0Lfp0rpudua13MFoT8NU", "created": "2024-03-14T08:10:15.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_fhYXl6ExKokyMqAlnDiz_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_ejaOwTOxyNQu5WrDeZnk", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 14600, "net_amount": 0, "amount_capturable": 14600, "amount_received": null, "connector": "paypal_test", "client_secret": "test_ejaOwTOxyNQu5WrDeZnk_secret_l6jUZkSzjkNpa8xnzwwj", "created": "2024-03-14T05:25:35.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_ejaOwTOxyNQu5WrDeZnk_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_MB9kqEtqMONlQEPHb1dT", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 12900, "net_amount": 0, "amount_capturable": 12900, "amount_received": null, "connector": "stripe_test", "client_secret": "test_MB9kqEtqMONlQEPHb1dT_secret_kSeuhHJkrZcBndgMWRP2", "created": "2024-03-14T05:02:09.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_MB9kqEtqMONlQEPHb1dT_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_kWl22oD2BdhPq3LM260p", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 11100, "net_amount": 0, "amount_capturable": 11100, "amount_received": null, "connector": "paypal_test", "client_secret": "test_kWl22oD2BdhPq3LM260p_secret_1KRPGPVx25PyjGcowDti", "created": "2024-03-14T04:27:59.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_kWl22oD2BdhPq3LM260p_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null }, { "payment_id": "test_uNRkJ3WbgCmZr7CF58Ev", "merchant_id": "merchant_1710153863", "status": "succeeded", "amount": 12900, "net_amount": 0, "amount_capturable": 12900, "amount_received": null, "connector": "stripe_test", "client_secret": "test_uNRkJ3WbgCmZr7CF58Ev_secret_yzc8nAG4qTdQVpSjmnwP", "created": "2024-03-14T03:43:12.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_uNRkJ3WbgCmZr7CF58Ev_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4TBk8LY9HGp5dGXqxFTF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "test", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ] } ```
[ "crates/router/src/core/payments/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4084
Bug: [BUG] : payments response has `payment_method_billing` even if not passed in request. ### Bug Description When a payment is created with `payment.billing`, in the response `payment.payment_method_data.billing` is also populated. ### Expected Behavior `payment.pament_method_data.billing` should be empty or null. ### Actual Behavior `payment.payment_method_data.billing` is not null, whereas it has the data of `payment.billing` ### Steps To Reproduce - Create a payment using the below curl ```bash curl --location 'https://integ-api.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_digX9Cd2d0ONVCCt2x8B1lgLLorGkw18S2gOR9fLzMu72hQmPpM7I01ppNJJXzZ6' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "26", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - The response should not have `payment.payment_method_data.billing`. - The response should have `payment.billing`. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b8a4c5dfc67..fb53e484afd 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2122,6 +2122,7 @@ pub mod payment_address { pub struct PaymentAddress { shipping: Option<api::Address>, billing: Option<api::Address>, + unified_payment_method_billing: Option<api::Address>, payment_method_billing: Option<api::Address>, } @@ -2131,20 +2132,26 @@ pub mod payment_address { billing: Option<api::Address>, payment_method_billing: Option<api::Address>, ) -> Self { - let payment_method_billing = match (payment_method_billing, billing.clone()) { - (Some(payment_method_billing), Some(order_billing)) => Some(api::Address { - address: payment_method_billing.address.or(order_billing.address), - phone: payment_method_billing.phone.or(order_billing.phone), - email: payment_method_billing.email.or(order_billing.email), - }), - (Some(payment_method_billing), None) => Some(payment_method_billing), - (None, Some(order_billing)) => Some(order_billing), - (None, None) => None, - }; + // Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing` + // The unified payment_method_billing will be used as billing address and passed to the connector module + // This unification is required in order to provide backwards compatibility + // so that if `payment.billing` is passed it should be sent to the connector module + let unified_payment_method_billing = + match (payment_method_billing.clone(), billing.clone()) { + (Some(payment_method_billing), Some(order_billing)) => Some(api::Address { + address: payment_method_billing.address.or(order_billing.address), + phone: payment_method_billing.phone.or(order_billing.phone), + email: payment_method_billing.email.or(order_billing.email), + }), + (Some(payment_method_billing), None) => Some(payment_method_billing), + (None, Some(order_billing)) => Some(order_billing), + (None, None) => None, + }; Self { shipping, billing, + unified_payment_method_billing, payment_method_billing, } } @@ -2154,6 +2161,10 @@ pub mod payment_address { } pub fn get_payment_method_billing(&self) -> Option<&api::Address> { + self.unified_payment_method_billing.as_ref() + } + + pub fn get_request_payment_method_billing(&self) -> Option<&api::Address> { self.payment_method_billing.as_ref() } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 315ddd3b39b..73d780c0960 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -467,7 +467,10 @@ where let payment_method_data_response = payment_method_data.map(|payment_method_data| { api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data, - billing: payment_data.address.get_payment_method_billing().cloned(), + billing: payment_data + .address + .get_request_payment_method_billing() + .cloned(), } }); diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 006c4503ce1..e9082299ab1 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -583,7 +583,7 @@ impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate { impl<'a> From<&'a domain::Address> for api_types::Address { fn from(address: &domain::Address) -> Self { - // If all the fields of address are none, then + // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() && address.line1.is_none() && address.line2.is_none() @@ -608,12 +608,19 @@ impl<'a> From<&'a domain::Address> for api_types::Address { }) }; - Self { - address: address_details, - phone: Some(api_types::PhoneDetails { + // If all the fields of phone are none, then pass the phone as None + let phone_details = if address.phone_number.is_none() && address.country_code.is_none() { + None + } else { + Some(api_types::PhoneDetails { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), - }), + }) + }; + + Self { + address: address_details, + phone: phone_details, email: address.email.clone().map(pii::Email::from), } } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js index d18cc474f87..cad157942d1 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js @@ -87,3 +87,11 @@ pm.test( .true; }, ); + +// Response body should not have "payment.billing" +pm.test( + "[POST]::/payments - Content check if 'payment.billing' is null", + function () { + pm.expect(jsonData?.billing).to.be.null + }, +); diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json index 7a755ed4e6e..83e3a58da2e 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json @@ -60,19 +60,6 @@ "email": "example@juspay.in" } }, - "billing": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "sundari", - "last_name": "sundari" - } - }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js index 3d51aaa49a8..93d36d988d4 100644 --- a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js +++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js @@ -97,3 +97,11 @@ pm.test( .true; }, ); + +// Response body should not have "payment_method_data.billing" +pm.test( + "[POST]::/payments - Content check if 'payment_method_data.billing' should be null", + function () { + pm.expect(jsonData?.payment_method_data?.billing).to.be.null; + }, +); diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index c3d6371fd7d..46829047bd2 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -2451,6 +2451,14 @@ " .true;", " },", ");", + "", + "// Response body should not have \"payment_method_data.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' should be null\",", + " function () {", + " pm.expect(jsonData?.payment_method_data?.billing).to.be.null;", + " },", + ");", "" ], "type": "text/javascript" @@ -20865,6 +20873,14 @@ " .true;", " },", ");", + "", + "// Response body should not have \"payment.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment.billing' is null\",", + " function () {", + " pm.expect(jsonData?.billing).to.be.null", + " },", + ");", "" ], "type": "text/javascript" @@ -20890,7 +20906,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments",
2024-03-14T04:37:42Z
## Description <!-- Describe your changes in detail --> This PR fixes the inconsistency in payments response. More details can be found in the linked issue. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Added postman test cases - Create a payment without `payment_method_billing`. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } }' ``` - Response ```json { "payment_id": "pay_ZjoHfCqtenTCCd0fBUEc", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_ZjoHfCqtenTCCd0fBUEc_secret_6SzPF2EQfTFVpedXJaqE", "created": "2024-03-15T09:37:12.679Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXCPD5R7gDAGff05AoM0mg", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXCPD5R7gDAGff05AoM0mg", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:52:12.679Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` - Create a payment with `payment_method_billing`. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } } }' ``` - Response ```json { "payment_id": "pay_4T2Q81rgIeAO7gOxpIQM", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_4T2Q81rgIeAO7gOxpIQM_secret_GXFlAK6whO0llT5nLQaf", "created": "2024-03-15T09:39:37.428Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXEkD5R7gDAGff1EBDw2dH", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXEkD5R7gDAGff1EBDw2dH", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:54:37.428Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` - Create a payment with both billing. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "address": { "state": "Karnataka", "zip": "94122", "country": "IN", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Chaser", "last_name": "Dough" }, "email": "example@juspay.in" } }' ``` - Response ( both billing should be different ) ```json { "payment_id": "pay_nsM4uQjQ3S9QbrjBDhzj", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_nsM4uQjQ3S9QbrjBDhzj_secret_iV3hnUtQwC95aWDhEcV0", "created": "2024-03-15T09:40:56.482Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": "Karnataka", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" } }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Chaser", "last_name": "Dough" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXG1D5R7gDAGff0sH2G6LI", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXG1D5R7gDAGff0sH2G6LI", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:55:56.482Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ```
74345212ed3052c54323ae143cd89a4b03b23d15
- Added postman test cases - Create a payment without `payment_method_billing`. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } }' ``` - Response ```json { "payment_id": "pay_ZjoHfCqtenTCCd0fBUEc", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_ZjoHfCqtenTCCd0fBUEc_secret_6SzPF2EQfTFVpedXJaqE", "created": "2024-03-15T09:37:12.679Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXCPD5R7gDAGff05AoM0mg", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXCPD5R7gDAGff05AoM0mg", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:52:12.679Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` - Create a payment with `payment_method_billing`. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } } }' ``` - Response ```json { "payment_id": "pay_4T2Q81rgIeAO7gOxpIQM", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_4T2Q81rgIeAO7gOxpIQM_secret_GXFlAK6whO0llT5nLQaf", "created": "2024-03-15T09:39:37.428Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXEkD5R7gDAGff1EBDw2dH", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXEkD5R7gDAGff1EBDw2dH", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:54:37.428Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` - Create a payment with both billing. ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000000101", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "address": { "state": "Karnataka", "zip": "94122", "country": "IN", "first_name": "Narayan", "last_name": "Doe" }, "email": "example@juspay.in" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Chaser", "last_name": "Dough" }, "email": "example@juspay.in" } }' ``` - Response ( both billing should be different ) ```json { "payment_id": "pay_nsM4uQjQ3S9QbrjBDhzj", "merchant_id": "merchant_1710395888", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_nsM4uQjQ3S9QbrjBDhzj_secret_iV3hnUtQwC95aWDhEcV0", "created": "2024-03-15T09:40:56.482Z", "currency": "USD", "customer_id": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0101", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": "40000000", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": "Karnataka", "first_name": "Narayan", "last_name": "Doe" }, "phone": null, "email": "example@juspay.in" } }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrisoff Street", "zip": "94122", "state": "California", "first_name": "Chaser", "last_name": "Dough" }, "phone": null, "email": "example@juspay.in" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3OuXG1D5R7gDAGff0sH2G6LI", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3OuXG1D5R7gDAGff0sH2G6LI", "payment_link": null, "profile_id": "pro_uMo0FiDFjCIAtLfdHK1J", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-15T09:55:56.482Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ```
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types/transformers.rs", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js", "postman/collection-dir/stripe...
juspay/hyperswitch
juspay__hyperswitch-4083
Bug: [FEATURE] : [Cybersource] Add Card holder name in dynamic field ### Feature Description Add Card holder name as required field in dynamic field ### Possible Implementation Add Card holder name as required field in dynamic field in `default.rs` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 5c2d62b40b8..f9d98647d1b 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -757,7 +757,8 @@ impl Default for super::settings::RequiredFields { enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from( + non_mandate: HashMap::new(), + common:HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), @@ -795,6 +796,15 @@ 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 { @@ -873,7 +883,6 @@ impl Default for super::settings::RequiredFields { ) ] ), - common:HashMap::new(), } ), ( @@ -2853,6 +2862,15 @@ 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 { @@ -4783,7 +4801,8 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserBank, value: None, } - ) + ), + ]), } ),
2024-03-13T19:33:13Z
## Description <!-- Describe your changes in detail --> add card holder name as a required field in dynamic fields for cyber source ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #4083 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a payment for Cybersource with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_NEqxtA08zn0qi3szJqYNmFXpQQt41BfwDpOE1sVucX37yJUN7jpR6QkmrlJCuWf5' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": false, "capture_method": "automatic", "customer_id": "shanks5", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "city": "SanFransico", "country": "AE", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "setup_future_usage": "off_session", "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone 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": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` - Retrieve payment method list for the merchant, card holder name should be present as required field <img width="1129" alt="Screenshot 2024-03-14 at 1 02 47 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/78879e1d-4f5d-4aa4-bb51-13020bee4e6e">
74345212ed3052c54323ae143cd89a4b03b23d15
- Create a payment for Cybersource with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_NEqxtA08zn0qi3szJqYNmFXpQQt41BfwDpOE1sVucX37yJUN7jpR6QkmrlJCuWf5' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": false, "capture_method": "automatic", "customer_id": "shanks5", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "city": "SanFransico", "country": "AE", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "setup_future_usage": "off_session", "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone 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": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` - Retrieve payment method list for the merchant, card holder name should be present as required field <img width="1129" alt="Screenshot 2024-03-14 at 1 02 47 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/78879e1d-4f5d-4aa4-bb51-13020bee4e6e">
[ "crates/router/src/configs/defaults.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4079
Bug: [FEATURE] [AUTHORIZEDOTNET] Add apple pay manual flow to dashboard ### Feature Description Apple pay manual flow needs to be added for authorizedotnet in the following dashboards: 1. Integ 2. Sandbox 3. Production ### Possible Implementation Apple pay manual flow needs to be added for authorizedotnet in the following dashboards by doing wasm config changes: 1. Integ 2. Sandbox 3. Production ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 58e54c36220..11025de310a 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -334,6 +334,8 @@ merchant_secret="Source verification key" payment_method_type = "CartesBancaires" [[authorizedotnet.debit]] payment_method_type = "UnionPay" +[[authorizedotnet.wallet]] + payment_method_type = "apple_pay" [[authorizedotnet.wallet]] payment_method_type = "google_pay" [[authorizedotnet.wallet]] @@ -345,6 +347,17 @@ key1="Transaction Key" merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" merchant_id="Google Pay Merchant ID" +[authorizedotnet.metadata.apple_pay.session_token_data] +certificate="Merchant Certificate (Base64 Encoded)" +certificate_keys="Merchant PrivateKey (Base64 Encoded)" +merchant_identifier="Apple Merchant Identifier" +display_name="Display Name" +initiative="Domain" +initiative_context="Domain Name" +[authorizedotnet.metadata.apple_pay.payment_request_data] +supported_networks=["visa","masterCard","amex","discover"] +merchant_capabilities=["supports3DS"] +label="apple" [authorizedotnet.connector_webhook_details] merchant_secret="Source verification key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 41facc9732f..079ead7e4ce 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -227,6 +227,8 @@ merchant_secret="Source verification key" payment_method_type = "CartesBancaires" [[authorizedotnet.debit]] payment_method_type = "UnionPay" +[[authorizedotnet.wallet]] + payment_method_type = "apple_pay" [[authorizedotnet.wallet]] payment_method_type = "google_pay" [[authorizedotnet.wallet]] @@ -239,6 +241,17 @@ key1="Transaction Key" merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" merchant_id="Google Pay Merchant ID" +[authorizedotnet.metadata.apple_pay.session_token_data] +certificate="Merchant Certificate (Base64 Encoded)" +certificate_keys="Merchant PrivateKey (Base64 Encoded)" +merchant_identifier="Apple Merchant Identifier" +display_name="Display Name" +initiative="Domain" +initiative_context="Domain Name" +[authorizedotnet.metadata.apple_pay.payment_request_data] +supported_networks=["visa","masterCard","amex","discover"] +merchant_capabilities=["supports3DS"] +label="apple" [authorizedotnet.connector_webhook_details] merchant_secret="Source verification key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index c93acee4736..6913885d3fd 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -334,6 +334,8 @@ merchant_secret="Source verification key" payment_method_type = "CartesBancaires" [[authorizedotnet.debit]] payment_method_type = "UnionPay" +[[authorizedotnet.wallet]] + payment_method_type = "apple_pay" [[authorizedotnet.wallet]] payment_method_type = "google_pay" [[authorizedotnet.wallet]] @@ -345,6 +347,17 @@ key1="Transaction Key" merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" merchant_id="Google Pay Merchant ID" +[authorizedotnet.metadata.apple_pay.session_token_data] +certificate="Merchant Certificate (Base64 Encoded)" +certificate_keys="Merchant PrivateKey (Base64 Encoded)" +merchant_identifier="Apple Merchant Identifier" +display_name="Display Name" +initiative="Domain" +initiative_context="Domain Name" +[authorizedotnet.metadata.apple_pay.payment_request_data] +supported_networks=["visa","masterCard","amex","discover"] +merchant_capabilities=["supports3DS"] +label="apple" [authorizedotnet.connector_webhook_details] merchant_secret="Source verification key"
2024-03-13T14:24:05Z
## Description <!-- Describe your changes in detail --> Apple pay manual flow is added for authorizedotnet in the following dashboards: 1. Integ 2. Sandbox 3. Production ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4079 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only Dashboard WASM Changes
a21d6d5e16730e0d12ea924066b4592c76f26bfd
Only Dashboard WASM Changes
[ "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/production.toml", "crates/connector_configs/toml/sandbox.toml" ]
juspay/hyperswitch
juspay__hyperswitch-4074
Bug: [BUG] `requires_cvv` being sent as `true` in customer payment methods list for off-session payments ### Bug Description When doing a customer payment methods list for an off-session payment, `requires_cvv` is received as `true`. ### Expected Behavior For off-session payments, `requires_cvv` should be false. ### Actual Behavior It's being sent as true by default ### Steps To Reproduce 1. Set up an MIT with any connector 2. Create an off-session payment 3. Do a customer payment methods list call ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 847950d4f45..4c38e41e9bb 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2736,6 +2736,16 @@ pub async fn list_customer_payment_method( } }; + let off_session_payment_flag = payment_intent + .as_ref() + .map(|pi| { + matches!( + pi.setup_future_usage, + Some(common_enums::FutureUsage::OffSession) + ) + }) + .unwrap_or(false); + let customer = db .find_customer_by_customer_id_merchant_id( customer_id, @@ -2872,7 +2882,8 @@ pub async fn list_customer_payment_method( bank_transfer: pmd, bank: bank_details, surcharge_details: None, - requires_cvv, + requires_cvv: requires_cvv + && !(off_session_payment_flag && pm.connector_mandate_details.is_some()), last_used_at: Some(pm.last_used_at), default_payment_method_set: customer.default_payment_method_id.is_some() && customer.default_payment_method_id == Some(pm.payment_method_id),
2024-03-13T11:47:24Z
## Description <!-- Describe your changes in detail --> This PR updates the logic to decide the `requires_cvv` parameter in the customer payment methods list api to also depend on whether the payment is an off-session payment. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> For off-session payments, the cvv is not required, so it should not be mandatory for off-session payments. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> List Customer Payment Methods for normal payment (requires_cvv = true): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/8e72d476-89a8-4e2b-ae11-b9a4074065be"> List Customer Payment Methods for off-session payment (requires_cvv = false): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/649bc7b9-5561-42aa-9564-119adc7d143d">
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
List Customer Payment Methods for normal payment (requires_cvv = true): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/8e72d476-89a8-4e2b-ae11-b9a4074065be"> List Customer Payment Methods for off-session payment (requires_cvv = false): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/649bc7b9-5561-42aa-9564-119adc7d143d">
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4069
Bug: [BUG] Give higher precedence to connector mandate id over network txn id for mandates ### Bug Description Recurring mandate payments with Adyen fail with a payment method not found error. ### Expected Behavior When doing recurring mandate payments with Adyen, the core should make the payment with the connector mandate id stored in the mandate object in DB. ### Actual Behavior Currently, if a mandate has both an associated network transaction id and connector mandate id, the core picks the network transaction id for recurring mandate transactions. This is the case for Adyen. ### Steps To Reproduce 1. Create a Merchant Account and an Adyen MCA 2. Create a mandate payment 3. Try to do a recurring mandate payment ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 2fd559680ea..fb80c0a1c48 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -508,8 +508,15 @@ impl .map_or(false, |future_usage| { matches!(future_usage, FutureUsage::OffSession) }) - && item.router_data.request.customer_acceptance.is_some() - { + && (item.router_data.request.customer_acceptance.is_some() + || item + .router_data + .request + .setup_mandate_details + .clone() + .map_or(false, |mandate_details| { + mandate_details.customer_acceptance.is_some() + })) { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 6e185ea66d8..5efbee0bc6b 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -301,14 +301,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_obj.network_transaction_id, mandate_obj.connector_mandate_ids, ) { - (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { - mandate_id: Some(mandate_obj.mandate_id), - mandate_reference_id: Some( - api_models::payments::MandateReferenceId::NetworkMandateId( - network_tx_id, - ), - ), - }), (_, Some(connector_mandate_id)) => connector_mandate_id .parse_value("ConnectorMandateId") .change_context(errors::ApiErrorResponse::MandateNotFound) @@ -324,6 +316,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> )) } }), + (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { + mandate_id: Some(mandate_obj.mandate_id), + mandate_reference_id: Some( + api_models::payments::MandateReferenceId::NetworkMandateId( + network_tx_id, + ), + ), + }), (_, _) => Ok(api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: None,
2024-03-13T10:30:25Z
## Description <!-- Describe your changes in detail --> Currently in the core, for a recurring mandate payment, if the mandate has both a network transaction ID and a connector mandate ID associated with it, the core picks the network transaction ID for making the recurring payment. This causes mandate payments to fail since we don't yet have support for making recurring mandate payments using a network transaction ID. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Recurring Mandate payment with Adyen Initial Mandate Payment: <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/c9701cef-ca32-4428-bc6a-b91feb026e7c"> Recurring Mandate payment (Succeeding): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6b75a147-7074-4ab0-b339-a11c66e64f68">
fad23ad032971497b07035c530397539413b7653
Recurring Mandate payment with Adyen Initial Mandate Payment: <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/c9701cef-ca32-4428-bc6a-b91feb026e7c"> Recurring Mandate payment (Succeeding): <img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6b75a147-7074-4ab0-b339-a11c66e64f68">
[ "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/core/payments/operations/payment_create.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4070
Bug: [BUG] Fix postman collections - [x] NMI: Scenarios 10 and 11 are run before 1 - [x] Bluesnap: Inconsistency of payment method being saved in saved card flow - [x] Checkout: Inconsistency of payment method being saved in saved card flow - [x]Adyen: Inconsistency of payment method being saved in saved card flow ## Solution - Remove `Copy` in Scenarios 10 and 11 form `.meta.json` to match with actual folder names - Set `random_number` in `pre_request.js` for Bluesnap connector to make `customer_id` unique
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json index 035bfeded8e..ad1de26c594 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json @@ -12,8 +12,8 @@ "Scenario8-Create a failure card payment with confirm true", "Scenario9-Update amount with automatic capture", "Scenario9a-Update amount with manual capture", - "Scenario10-Create a mandate and recurring payment Copy", - "Scenario11-Refund recurring payment Copy", + "Scenario10-Create a mandate and recurring payment", + "Scenario11-Refund recurring payment", "Scenario12-Add card flow", "Scenario13-Don't Pass CVV for save card flow and verify success payment", "Scenario14-Save card payment with manual capture", diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json index e8160e482fe..137ccbe1a23 100644 --- a/postman/collection-json/bluesnap.postman_collection.json +++ b/postman/collection-json/bluesnap.postman_collection.json @@ -837,6 +837,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -1811,6 +1821,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -2444,6 +2464,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -3583,6 +3613,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { diff --git a/postman/collection-json/checkout.postman_collection.json b/postman/collection-json/checkout.postman_collection.json index 0a1afbdd04a..cdb94b4a84b 100644 --- a/postman/collection-json/checkout.postman_collection.json +++ b/postman/collection-json/checkout.postman_collection.json @@ -899,6 +899,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -1906,6 +1916,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -2532,6 +2552,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -3176,6 +3206,16 @@ { "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json index d25030fad27..fa1dbac954f 100644 --- a/postman/collection-json/nmi.postman_collection.json +++ b/postman/collection-json/nmi.postman_collection.json @@ -815,7 +815,7 @@ "name": "Happy Cases", "item": [ { - "name": "Scenario10-Create a mandate and recurring payment", + "name": "Scenario1-Create payment with confirm true", "item": [ { "name": "Payments - Create", @@ -824,7 +824,7 @@ "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -896,7 +896,7 @@ " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", @@ -905,22 +905,6 @@ " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -946,7 +930,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -1039,22 +1023,6 @@ " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1095,15 +1063,20 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario2-Create payment with confirm false", + "item": [ { - "name": "Recurring Payments - Create", + "name": "Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -1175,39 +1148,136 @@ " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", " },", " );", "}", + "" + ], + "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my last payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, + "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 - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", "", - "// Response body should have \"mandate_id\"", + "// Validate if response header has matching content-type", "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", " },", ");", "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", "", - "// Response body should have \"payment_method_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", - " },", - ");", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", "" ], "type": "text/javascript" @@ -1215,6 +1285,26 @@ } ], "request": { + "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": [ { @@ -1233,23 +1323,32 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"client_secret\":\"{{client_secret}}\"}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "Payments - Retrieve-copy", + "name": "Payments - Retrieve", "event": [ { "listen": "test", @@ -1317,31 +1416,15 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1386,7 +1469,7 @@ ] }, { - "name": "Scenario11-Refund recurring payment", + "name": "Scenario2a-Create payment with confirm false card holder name null", "item": [ { "name": "Payments - Create", @@ -1395,7 +1478,7 @@ "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -1405,9 +1488,6 @@ "listen": "test", "script": { "exec": [ - "// 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;", @@ -1470,31 +1550,15 @@ " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1520,7 +1584,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -1536,26 +1600,38 @@ "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Confirm", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -1604,31 +1680,15 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1636,27 +1696,55 @@ } ], "request": { - "method": "GET", + "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": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } + ":id", + "confirm" ], "variable": [ { @@ -1666,44 +1754,31 @@ } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "Recurring Payments - Create", + "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ - "// 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.test(\"[GET]::/payments/:id - 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.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(\"[POST]::/payments - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -1752,39 +1827,15 @@ " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"payment_method_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1792,60 +1843,76 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario2b-Create payment with confirm false card holder name empty", + "item": [ { - "name": "Payments - Retrieve-copy", + "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -1894,31 +1961,15 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -1926,42 +1977,41 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ { - "key": "Accept", + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "Refunds - Create", + "name": "Payments - Confirm", "event": [ { "listen": "prerequest", @@ -1976,19 +2026,24 @@ "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.test(\"[POST]::/payments - 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\",", - " );", + "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", @@ -1997,45 +2052,80 @@ " 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);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"pending\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"pending\");", - " },", + "// 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.\",", " );", "}", "", - "// Response body should have value for \"amount\"", + "// 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\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(amount);", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", - "}", - "" + "}" ], "type": "text/javascript" } } ], "request": { + "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": [ { @@ -2054,91 +2144,108 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "description": "To create a refund against an already processed payment" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "Refunds - Retrieve", + "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const refund_amount = pm.environment.get(\"amount\");", - "", "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + "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]::/refunds/:id - Content-Type is application/json\", function () {", + "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 refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + "// 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.\",", " );", "}", "", - "// Response body should have value for \"refund_amount\"", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(refund_amount);", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", - "}", - "" + "}" ], "type": "text/javascript" } @@ -2153,30 +2260,36 @@ } ], "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] } ] }, { - "name": "Scenario1-Create payment with confirm true", + "name": "Scenario3-Create payment without PMD", "item": [ { "name": "Payments - Create", @@ -2257,12 +2370,12 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", @@ -2291,7 +2404,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -2307,26 +2420,38 @@ "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Confirm", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -2375,12 +2500,12 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", @@ -2391,27 +2516,55 @@ } ], "request": { - "method": "GET", + "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": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } + ":id", + "confirm" ], "variable": [ { @@ -2421,46 +2574,31 @@ } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] - } - ] - }, - { - "name": "Scenario2-Create payment with confirm false", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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(\"[POST]::/payments - Content-Type is application/json\", function () {", + "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(\"[POST]::/payments - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -2509,12 +2647,12 @@ " );", "}", "", - "// Response body should have value \"requires_confirmation\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", @@ -2525,63 +2663,78 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my last payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario4-Create payment with Manual capture", + "item": [ { - "name": "Payments - Confirm", + "name": "Payments - Create", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ + "pm.environment.set(\"amount\", pm.response.json().amount);", + "", "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "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/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -2630,10 +2783,10 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_capture\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"processing\");", " },", @@ -2646,26 +2799,6 @@ } ], "request": { - "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": [ { @@ -2684,27 +2817,18 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "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": [] }, @@ -2780,9 +2904,9 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", " },", " );", "}", @@ -2826,20 +2950,14 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario2a-Create payment with confirm false card holder name null", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Capture", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -2849,20 +2967,26 @@ "listen": "test", "script": { "exec": [ + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "pm.test(", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", "", "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -2911,142 +3035,32 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "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 - Confirm", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"{{amount}}\" for \"amount\"", + "if (jsonData?.amount) {", + " pm.test(", + " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '{{amount}}'\",", + " function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + " },", " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", - "if (jsonData?.status) {", + "// Response body should have value \"{{amount}}\" for \"amount_received\"", + "if (jsonData?.amount_received) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.amount_received).to.eql(amount);", " },", " );", "}", @@ -3057,26 +3071,6 @@ } ], "request": { - "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": [ { @@ -3095,17 +3089,17 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id/capture", "host": [ "{{baseUrl}}" ], "path": [ "payments", ":id", - "confirm" + "capture" ], "variable": [ { @@ -3115,12 +3109,12 @@ } ] }, - "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" + "description": "To capture the funds for an uncaptured payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Retrieve-copy", "event": [ { "listen": "test", @@ -3191,7 +3185,7 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", @@ -3241,7 +3235,7 @@ ] }, { - "name": "Scenario2b-Create payment with confirm false card holder name empty", + "name": "Scenario5-Void the payment", "item": [ { "name": "Payments - Create", @@ -3322,12 +3316,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"requires_capture\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", @@ -3356,7 +3350,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -3372,38 +3366,26 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -3452,104 +3434,89 @@ " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"cancelled\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", " },", " );", - "}" + "}", + "" ], "type": "text/javascript" } } ], "request": { - "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", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id", - "confirm" + ":id" ], - "variable": [ + "query": [ { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "key": "force_sync", + "value": "true" + } + ], + "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Cancel", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "pm.test(", + " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", "", "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -3572,19 +3539,6 @@ " );", "}", "", - "// 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);", @@ -3598,42 +3552,51 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"cancelled\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", - "}" + "}", + "" ], "type": "text/javascript" } } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"cancellation_reason\":\"user_cancel\"}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id/cancel", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } + ":id", + "cancel" ], "variable": [ { @@ -3643,46 +3606,31 @@ } ] }, - "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" + "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" }, "response": [] - } - ] - }, - { - "name": "Scenario3-Create payment without PMD", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Retrieve-copy", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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(\"[POST]::/payments - Content-Type is application/json\", function () {", + "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(\"[POST]::/payments - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -3731,12 +3679,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"cancelled\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", " },", " );", "}", @@ -3747,46 +3695,53 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario6-Refund full payment", + "item": [ { - "name": "Payments - Confirm", + "name": "Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -3796,23 +3751,23 @@ "listen": "test", "script": { "exec": [ + "// 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/:id/confirm - Status code is 2xx\", function () {", + "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/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -3864,7 +3819,7 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"processing\");", " },", @@ -3877,26 +3832,6 @@ } ], "request": { - "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": [ { @@ -3915,27 +3850,18 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "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": [] }, @@ -4008,10 +3934,10 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", @@ -4057,20 +3983,14 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario4-Create payment with Manual capture", - "item": [ + }, { - "name": "Payments - Create", + "name": "Refunds - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -4080,76 +4000,56 @@ "listen": "test", "script": { "exec": [ - "pm.environment.set(\"amount\", pm.response.json().amount);", + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", "", "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/refunds - 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);", + "// 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 {{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,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"pending\");", + " },", " );", "}", "", - "// Response body should have value \"requires_capture\" for \"status\"", + "// Response body should have value for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.amount).to.eql(amount);", " },", " );", "}", @@ -4178,96 +4078,78 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds" ] }, - "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" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Refunds - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ + "// Get the value of 'amount' from the environment", + "const refund_amount = pm.environment.get(\"amount\");", + "", "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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]::/payments/:id - Content-Type is application/json\", function () {", + "pm.test(\"[GET]::/refunds/: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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"{{refund_amount}}\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '{{refund_amount}}'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " pm.expect(jsonData.amount).to.eql(refund_amount);", " },", " );", "}", @@ -4286,39 +4168,39 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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": "Scenario7-Partial refund", + "item": [ { - "name": "Payments - Capture", + "name": "Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -4328,26 +4210,20 @@ "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", - "", "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + "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/:id/capture - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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/:id/capture - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -4396,35 +4272,15 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", - "", - "// Response body should have value \"{{amount}}\" for \"amount\"", - "if (jsonData?.amount) {", - " pm.test(", - " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '{{amount}}'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - " },", - " );", - "}", - "", - "// Response body should have value \"{{amount}}\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",", - " function () {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - " },", - " );", - "}", "" ], "type": "text/javascript" @@ -4450,32 +4306,23 @@ "language": "json" } }, - "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/capture", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "description": "To capture the funds for an uncaptured payment" + "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-copy", + "name": "Payments - Retrieve", "event": [ { "listen": "test", @@ -4543,10 +4390,10 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", @@ -4592,20 +4439,14 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario5-Void the payment", - "item": [ + }, { - "name": "Payments - Create", + "name": "Refunds - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -4616,73 +4457,52 @@ "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/refunds - 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);", + "// 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 {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_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.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"pending\");", + " },", " );", "}", "", - "// 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_capture\" for \"status\"", + "// Response body should have value \"540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.amount).to.eql(100);", " },", " );", "}", @@ -4711,96 +4531,75 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":100,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds" ] }, - "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" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Refunds - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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]::/payments/:id - Content-Type is application/json\", function () {", + "pm.test(\"[GET]::/refunds/: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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"cancelled\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " pm.expect(jsonData.amount).to.eql(100);", " },", " );", "}", @@ -4819,34 +4618,28 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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": "Payments - Cancel", + "name": "Refunds - Create-copy", "event": [ { "listen": "prerequest", @@ -4862,23 +4655,15 @@ "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", + "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]::/payments/:id/cancel - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "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", @@ -4887,38 +4672,35 @@ " 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);", + "// 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 {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"pending\");", + " },", " );", "}", "", - "// Response body should have value \"cancelled\" for \"status\"", + "// Response body should have value \"1000\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.amount).to.eql(10);", " },", " );", "}", @@ -4947,27 +4729,110 @@ "language": "json" } }, - "raw": "{\"cancellation_reason\":\"user_cancel\"}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":10,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "cancel" + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + }, + { + "name": "Refunds - Retrieve-copy", + "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.\",", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// Response body should have value \"6540\" for \"amount\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",", + " function () {", + " pm.expect(jsonData.amount).to.eql(10);", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/refunds/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund id" } ] }, - "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" + "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": [] }, @@ -5040,15 +4905,20 @@ " );", "}", "", - "// Response body should have value \"cancelled\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"cancelled\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", + "", + "// Response body should have \"refunds\"", + "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {", + " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;", + "});", "" ], "type": "text/javascript" @@ -5093,7 +4963,7 @@ ] }, { - "name": "Scenario6-Refund full payment", + "name": "Scenario8-Create a failure card payment with confirm true", "item": [ { "name": "Payments - Create", @@ -5112,9 +4982,6 @@ "listen": "test", "script": { "exec": [ - "// 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;", @@ -5180,9 +5047,38 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", + " pm.expect(jsonData.status).to.eql(\"failed\");", + " },", + " );", + "}", + "", + "// 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;", + " },", + ");", + "", + "// Response body should have value \"200\" for \"error_code\"", + "if (jsonData?.error_code) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",", + " function () {", + " pm.expect(jsonData.error_code).to.eql(\"200\");", + " },", + " );", + "}", + "", + "// Response body should have value \"message - DECLINE\"", + "if (jsonData?.error_message) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",", + " function () {", + " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");", " },", " );", "}", @@ -5211,7 +5107,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -5229,6 +5125,15 @@ { "name": "Payments - Retrieve", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { @@ -5298,9 +5203,38 @@ "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"failed\");", + " },", + " );", + "}", + "", + "// 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;", + " },", + ");", + "", + "// Response body should have value \"200\" for \"error_code\"", + "if (jsonData?.error_code) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",", + " function () {", + " pm.expect(jsonData.error_code).to.eql(\"200\");", + " },", + " );", + "}", + "", + "// Response body should have value \"message - DECLINE\"", + "if (jsonData?.error_message) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",", + " function () {", + " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");", " },", " );", "}", @@ -5344,14 +5278,20 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario9-Update amount with automatic capture", + "item": [ { - "name": "Refunds - Create", + "name": "Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -5361,59 +5301,65 @@ "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", + "// 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]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "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) {}", + "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,", - " );", + "// 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 {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"pending\");", - " },", - " );", - "}", "", - "// Response body should have value for \"amount\"", + "// 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.');", + "};", + "", + "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + "})};", "" ], "type": "text/javascript" @@ -5439,81 +5385,70 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments" ] }, - "description": "To create a refund against an already processed payment" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "Refunds - Retrieve", + "name": "Payments - Update", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "// Get the value of 'amount' from the environment", + "pm.environment.set(\"another_random_number\", _.random(100, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ + "// Set the environment variable 'amount' with the value from the response", + "pm.environment.set(\"amount\", pm.response.json().amount);", + "", "// Get the value of 'amount' from the environment", - "const refund_amount = pm.environment.get(\"amount\");", + "const updated_amount = pm.environment.get(\"amount\");", "", - "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "pm.test(\"[POST]::/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(\"[POST]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", "", - "// 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.\",", - " );", - "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", + "// Parse the JSON response", + "var jsonData = pm.response.json();", + "", + "// Check if the 'amount' is equal to \"updated_amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {", + " pm.expect(jsonData.amount).to.eql(updated_amount);", + "});", + "", "", - "// Response body should have value \"{{refund_amount}}\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '{{refund_amount}}'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(refund_amount);", - " },", - " );", - "}", "" ], "type": "text/javascript" @@ -5521,47 +5456,53 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" + }, "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_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" + "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " }, "response": [] - } - ] - }, - { - "name": "Scenario7-Partial refund", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Confirm", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", "" ], "type": "text/javascript" @@ -5571,77 +5512,45 @@ "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", "", - "// 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 status 2xx ", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "// 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\");", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", + "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.\",", - " );", - "}", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", "", - "// 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.\",", - " );", - "}", + "//// Response body should have value \"processing\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + "})};", "", - "// 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\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", + "// Check if the 'amount' is equal to \"amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + "});", + "", + "//// Response body should have value \"amount_received\" for \"amount\"", + "if (jsonData?.amount_received) {", + "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + "})};", "" ], "type": "text/javascript" @@ -5649,6 +5558,26 @@ } ], "request": { + "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": [ { @@ -5658,6 +5587,12 @@ { "key": "Accept", "value": "application/json" + }, + { + "key": "publishable_key", + "value": "", + "type": "text", + "disabled": true } ], "body": { @@ -5667,99 +5602,109 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}" + } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { "name": "Payments - Retrieve", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", + "// Validate status 2xx ", "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\",", - " );", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", "});", "", - "// Validate if response has JSON Body", + "// Validate if response has JSON Body ", "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", + "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,", - " );", + " 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.\",", - " );", - "}", + " 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,", - " );", + " 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.\",", - " );", - "}", + " 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,", - " );", + " 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.\",", - " );", - "}", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "//// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + "})};", + "", + "", + "// Check if the 'amount' is equal to \"amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + "});", + "", + "//// Response body should have value \"amount_received\" for \"amount\"", + "if (jsonData?.amount_received) {", + "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + "})};", "" ], "type": "text/javascript" @@ -5800,14 +5745,20 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario9a-Update amount with manual capture", + "item": [ { - "name": "Refunds - Create", + "name": "Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", "" ], "type": "text/javascript" @@ -5817,56 +5768,65 @@ "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "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) {}", + "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,", - " );", + "// 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 {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"pending\");", - " },", - " );", - "}", "", - "// Response body should have value \"540\" for \"amount\"", + "// 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.');", + "};", + "", + "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(100);", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + "})};", "" ], "type": "text/javascript" @@ -5892,78 +5852,70 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":100,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments" ] }, - "description": "To create a refund against an already processed payment" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "Refunds - Retrieve", + "name": "Payments - Update", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "// Get the value of 'amount' from the environment", + "pm.environment.set(\"another_random_number\", _.random(100, 100000));", + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Set the environment variable 'amount' with the value from the response", + "pm.environment.set(\"amount\", pm.response.json().amount);", + "", + "// Get the value of 'amount' from the environment", + "const updated_amount = pm.environment.get(\"amount\");", + "", + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "pm.test(\"[POST]::/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(\"[POST]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", "", - "// 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.\",", - " );", - "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", + "// Parse the JSON response", + "var jsonData = pm.response.json();", + "", + "// Check if the 'amount' is equal to \"updated_amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {", + " pm.expect(jsonData.amount).to.eql(updated_amount);", + "});", + "", "", - "// Response body should have value \"6540\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(100);", - " },", - " );", - "}", "" ], "type": "text/javascript" @@ -5971,36 +5923,48 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" + }, "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_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" + "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " }, "response": [] }, { - "name": "Refunds - Create-copy", + "name": "Payments - Confirm", "event": [ { "listen": "prerequest", @@ -6015,56 +5979,45 @@ "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", + "// 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]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "pm.test(\"[POST]::/payments/:id/confirm - 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.\",", - " );", - "}", + "try {jsonData = pm.response.json();}catch(e){}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"pending\");", - " },", - " );", - "}", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", "", - "// Response body should have value \"1000\" for \"amount\"", + "//// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(10);", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + "})};", + "", + "", + "// Check if the 'amount' is equal to \"amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + "});", + "", + "//// Response body should have value \"amount_received\" for \"amount\"", + "if (jsonData?.amount_received) {", + "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + "})};", "" ], "type": "text/javascript" @@ -6072,6 +6025,26 @@ } ], "request": { + "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": [ { @@ -6081,6 +6054,12 @@ { "key": "Accept", "value": "application/json" + }, + { + "key": "publishable_key", + "value": "", + "type": "text", + "disabled": true } ], "body": { @@ -6090,78 +6069,109 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":10,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}" + } ] }, - "description": "To create a refund against an already processed payment" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "Refunds - Retrieve-copy", + "name": "Payments - Retrieve", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", + "// 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]::/refunds/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "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) {}", + "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,", - " );", + "// 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 {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", "", - "// Response body should have value \"6540\" for \"amount\"", + "// 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_capture\" for \"status\"", "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(10);", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + "})};", + "", + "", + "// Check if the 'amount' is equal to \"amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + "});", + "", + "//// Response body should have value \"amount_received\" for \"amount\"", + "if (jsonData?.amount_received) {", + "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + "})};", "" ], "type": "text/javascript" @@ -6177,47 +6187,68 @@ } ], "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] }, { - "name": "Payments - Retrieve-copy", + "name": "Payments - Capture", "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, { "listen": "test", "script": { "exec": [ + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "pm.test(", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", "", "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -6266,39 +6297,188 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", "", - "// Response body should have \"refunds\"", - "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {", - " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;", + "// Validate the connector", + "pm.test(\"[POST]::/payments - connector\", function () {", + " pm.expect(jsonData.connector).to.eql(\"nmi\");", "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", - "host": [ - "{{baseUrl}}" - ], + "", + "// Response body should have value \"amount\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",", + " function () {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + " },", + " );", + "}", + "", + "// Response body should have value \"0\" for \"amount_capturable\"", + "if (jsonData?.amount_capturable) {", + " pm.test(", + " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",", + " function () {", + " pm.expect(jsonData.amount_capturable).to.eql(amount);", + " },", + " );", + "}", + "" + ], + "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_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/capture", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "capture" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To capture the funds for an uncaptured payment" + }, + "response": [] + }, + { + "name": "Payments - Retrieve Copy", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", + "// 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 \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + "})};", + "", + "", + "// Check if the 'amount' is equal to \"amount\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", + " pm.expect(jsonData.amount).to.eql(amount);", + "});", + "", + "//// Response body should have value \"amount_received\" for \"amount\"", + "if (jsonData?.amount_received) {", + "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", + " pm.expect(jsonData.amount_received).to.eql(amount);", + "})};", + "" + ], + "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" @@ -6324,7 +6504,7 @@ ] }, { - "name": "Scenario8-Create a failure card payment with confirm true", + "name": "Scenario10-Create a mandate and recurring payment", "item": [ { "name": "Payments - Create", @@ -6333,7 +6513,7 @@ "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "pm.environment.set(\"random_number\", _.random(100, 100000));", "" ], "type": "text/javascript" @@ -6405,44 +6585,31 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"failed\");", + " pm.expect(jsonData.status).to.eql(\"processing\");", " },", " );", "}", "", - "// Response body should have \"connector_transaction_id\"", + "// Response body should have \"mandate_id\"", "pm.test(", - " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", " function () {", - " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", - " .true;", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", " },", ");", "", - "// Response body should have value \"200\" for \"error_code\"", - "if (jsonData?.error_code) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",", - " function () {", - " pm.expect(jsonData.error_code).to.eql(\"200\");", - " },", - " );", - "}", - "", - "// Response body should have value \"message - DECLINE\"", - "if (jsonData?.error_message) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",", - " function () {", - " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");", - " },", - " );", - "}", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -6468,7 +6635,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -6486,15 +6653,6 @@ { "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { @@ -6564,45 +6722,32 @@ "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"failed\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have \"connector_transaction_id\"", + "// Response body should have \"mandate_id\"", "pm.test(", - " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", " function () {", - " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", - " .true;", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", " },", ");", "", - "// Response body should have value \"200\" for \"error_code\"", - "if (jsonData?.error_code) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",", - " function () {", - " pm.expect(jsonData.error_code).to.eql(\"200\");", - " },", - " );", - "}", - "", - "// Response body should have value \"message - DECLINE\"", - "if (jsonData?.error_message) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",", - " function () {", - " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");", - " },", - " );", - "}", - "" - ], - "type": "text/javascript" - } + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", + "" + ], + "type": "text/javascript" + } } ], "request": { @@ -6639,20 +6784,15 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario9-Update amount with automatic capture", - "item": [ + }, { - "name": "Payments - Create", + "name": "Recurring Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ - "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "pm.environment.set(\"random_number\", _.random(100, 100000));", "" ], "type": "text/javascript" @@ -6662,256 +6802,101 @@ "listen": "test", "script": { "exec": [ - "// Set the environment variable 'amount' with the value from the response", - "pm.environment.set(\"amount\", pm.response.json().amount);", - "", - "// Validate status 2xx ", + "// Validate status 2xx", "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\");", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", "});", "", - "// Validate if response has JSON Body ", + "// Validate if response has JSON Body", "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " 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.');", - "};", - "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + " 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 {{customer_id}}, as jsonData.customer_id 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\");", - "})};", - "" - ], - "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\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "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 - Update", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "// Get the value of 'amount' from the environment", - "pm.environment.set(\"another_random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Set the environment variable 'amount' with the value from the response", - "pm.environment.set(\"amount\", pm.response.json().amount);", - "", - "// Get the value of 'amount' from the environment", - "const updated_amount = pm.environment.get(\"amount\");", - "", - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Parse the JSON response", - "var jsonData = pm.response.json();", - "", - "// Check if the 'amount' is equal to \"updated_amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {", - " pm.expect(jsonData.amount).to.eql(updated_amount);", - "});", - "", - "", - "" - ], - "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\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } - ] - }, - "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " - }, - "response": [] - }, - { - "name": "Payments - Confirm", - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", - "", - "// 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\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "//// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"processing\" for \"status\"", "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - "})};", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", "", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", "", - "// Check if the 'amount' is equal to \"amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - "});", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "", - "//// Response body should have value \"amount_received\" for \"amount\"", - "if (jsonData?.amount_received) {", - "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - "})};", + "// Response body should have \"payment_method_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -6919,26 +6904,6 @@ } ], "request": { - "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": [ { @@ -6948,12 +6913,6 @@ { "key": "Accept", "value": "application/json" - }, - { - "key": "publishable_key", - "value": "", - "type": "text", - "disabled": true } ], "body": { @@ -6963,109 +6922,115 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } + "payments" ] }, - "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" + "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", + "name": "Payments - Retrieve-copy", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", - "", - "// Validate status 2xx ", + "// Validate status 2xx", "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\");", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", "});", "", - "// Validate if response has JSON Body ", + "// Validate if response has JSON Body", "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " 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);", + " 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.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "//// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - "})};", - "", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", "", - "// Check if the 'amount' is equal to \"amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - "});", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", "", - "//// Response body should have value \"amount_received\" for \"amount\"", - "if (jsonData?.amount_received) {", - "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - "})};", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -7110,7 +7075,7 @@ ] }, { - "name": "Scenario9a-Update amount with manual capture", + "name": "Scenario11-Refund recurring payment", "item": [ { "name": "Payments - Create", @@ -7132,62 +7097,93 @@ "// Set the environment variable 'amount' with the value from the response", "pm.environment.set(\"amount\", pm.response.json().amount);", "", - "// Validate status 2xx ", + "// Validate status 2xx", "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\");", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", "});", "", - "// Validate if response has JSON Body ", + "// Validate if response has JSON Body", "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " 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);", + " 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.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"processing\" 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\");", - "})};", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", + "", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -7213,7 +7209,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -7229,54 +7225,99 @@ "response": [] }, { - "name": "Payments - Update", + "name": "Payments - Retrieve", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "// Get the value of 'amount' from the environment", - "pm.environment.set(\"another_random_number\", _.random(100, 100000));", - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ - "// Set the environment variable 'amount' with the value from the response", - "pm.environment.set(\"amount\", pm.response.json().amount);", - "", - "// Get the value of 'amount' from the environment", - "const updated_amount = pm.environment.get(\"amount\");", - "", - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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(\"[POST]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "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(\"[POST]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "// 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) {}", "", - "// Parse the JSON response", - "var jsonData = pm.response.json();", + "// 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.\",", + " );", + "}", "", - "// Check if the 'amount' is equal to \"updated_amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {", - " pm.expect(jsonData.amount).to.eql(updated_amount);", - "});", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"Succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", "", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -7284,28 +7325,15 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], @@ -7313,24 +7341,32 @@ "payments", ":id" ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], "variable": [ { "key": "id", - "value": "{{payment_id}}" + "value": "{{payment_id}}", + "description": "(Required) unique payment id" } ] }, - "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] }, { - "name": "Payments - Confirm", + "name": "Recurring Payments - Create", "event": [ { "listen": "prerequest", "script": { "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", "" ], "type": "text/javascript" @@ -7340,45 +7376,104 @@ "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", + "// 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/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "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){}", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - 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.\",", + " );", + "}", "", - "//// Response body should have value \"processing\" for \"status\"", + "// 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\" for \"status\"", "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - "})};", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"processing\");", + " },", + " );", + "}", "", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", "", - "// Check if the 'amount' is equal to \"amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - "});", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "", - "//// Response body should have value \"amount_received\" for \"amount\"", - "if (jsonData?.amount_received) {", - "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - "})};", + "// Response body should have \"payment_method_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -7386,26 +7481,6 @@ } ], "request": { - "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": [ { @@ -7415,12 +7490,6 @@ { "key": "Accept", "value": "application/json" - }, - { - "key": "publishable_key", - "value": "", - "type": "text", - "disabled": true } ], "body": { @@ -7430,109 +7499,115 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}" + "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } + "payments" ] }, - "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" + "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", + "name": "Payments - Retrieve-copy", "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, { "listen": "test", "script": { "exec": [ - "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", - "", - "// Validate status 2xx ", + "// Validate status 2xx", "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\");", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", "});", "", - "// Validate if response has JSON Body ", + "// Validate if response has JSON Body", "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " 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);", + " 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.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "//// Response body should have value \"requires_capture\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", - "})};", - "", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", "", - "// Check if the 'amount' is equal to \"amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - "});", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", "", - "//// Response body should have value \"amount_received\" for \"amount\"", - "if (jsonData?.amount_received) {", - "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - "})};", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -7575,7 +7650,7 @@ "response": [] }, { - "name": "Payments - Capture", + "name": "Refunds - Create", "event": [ { "listen": "prerequest", @@ -7594,23 +7669,15 @@ "const amount = pm.environment.get(\"amount\");", "", "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + "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]::/payments/:id/capture - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "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", @@ -7619,76 +7686,35 @@ " 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);", + "// 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 {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// Response body should have value \"processing\" for \"status\"", + "// Response body should have value \"pending\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"processing\");", - " },", - " );", - "}", - "", - "// Validate the connector", - "pm.test(\"[POST]::/payments - connector\", function () {", - " pm.expect(jsonData.connector).to.eql(\"nmi\");", - "});", - "", - "// Response body should have value \"amount\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",", + " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",", " function () {", - " pm.expect(jsonData.amount_received).to.eql(amount);", + " pm.expect(jsonData.status).to.eql(\"pending\");", " },", " );", "}", "", - "// Response body should have value \"0\" for \"amount_capturable\"", - "if (jsonData?.amount_capturable) {", + "// Response body should have value for \"amount\"", + "if (jsonData?.status) {", " pm.test(", - " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",", " function () {", - " pm.expect(jsonData.amount_capturable).to.eql(amount);", + " pm.expect(jsonData.amount).to.eql(amount);", " },", " );", "}", @@ -7717,32 +7743,23 @@ "language": "json" } }, - "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/capture", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "refunds" ] }, - "description": "To capture the funds for an uncaptured payment" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Retrieve Copy", + "name": "Refunds - Retrieve", "event": [ { "listen": "prerequest", @@ -7758,69 +7775,58 @@ "script": { "exec": [ "// Get the value of 'amount' from the environment", - "const amount = pm.environment.get(\"amount\");", + "const refund_amount = pm.environment.get(\"amount\");", "", - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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]::/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();", + "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 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.');", - "};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", "", - "// 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);", + "// 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 {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", "", - "//// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - "})};", - "", - "", - "// Check if the 'amount' is equal to \"amount\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {", - " pm.expect(jsonData.amount).to.eql(amount);", - "});", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", "", - "//// Response body should have value \"amount_received\" for \"amount\"", - "if (jsonData?.amount_received) {", - "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {", - " pm.expect(jsonData.amount_received).to.eql(amount);", - "})};", + "// Response body should have value for \"refund_amount\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",", + " function () {", + " pm.expect(jsonData.amount).to.eql(refund_amount);", + " },", + " );", + "}", "" ], "type": "text/javascript" @@ -7836,29 +7842,23 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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": [] }
2024-03-13T10:26:04Z
## Description <!-- Describe your changes in detail --> - NMI: Removed `Copy` from `.meta.json` to fix `Scenario 10` an `11` from running before `Scenario 1` - Bluesnap: Make `customer_id` unique to avoid payment method from being saved Closes #4070 > [!NOTE] > `.json` files are auto-generated ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - NMI (mandates are failing. @Aprabhat19 is looking into it) <img width="1240" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/c1493bb8-abc1-4c7b-900a-9910c594ed59"> <img width="1084" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e3d7e602-891d-4526-9840-ceb41c439dbd"> - Bluesnap <img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/52bca980-32a2-43fd-9783-2dcddcc6abdd"> - Checkout <img width="479" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/532b1bf8-7da0-4ad9-93d8-0a0a730e1852"> Wrote a script: <img width="575" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e636435b-5e37-4349-9353-93cf7d6de054"> NMI failed as mentioned above: <img width="327" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/a19d1e87-61f3-4295-984f-c5aa26681bfa">
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
- NMI (mandates are failing. @Aprabhat19 is looking into it) <img width="1240" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/c1493bb8-abc1-4c7b-900a-9910c594ed59"> <img width="1084" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e3d7e602-891d-4526-9840-ceb41c439dbd"> - Bluesnap <img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/52bca980-32a2-43fd-9783-2dcddcc6abdd"> - Checkout <img width="479" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/532b1bf8-7da0-4ad9-93d8-0a0a730e1852"> Wrote a script: <img width="575" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e636435b-5e37-4349-9353-93cf7d6de054"> NMI failed as mentioned above: <img width="327" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/a19d1e87-61f3-4295-984f-c5aa26681bfa">
[ "postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js", "postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js", "postman...
juspay/hyperswitch
juspay__hyperswitch-4072
Bug: add dispute events to global search indexes add dispute events to global search indexes
diff --git a/config/config.example.toml b/config/config.example.toml index daf554f00ad..b5344882913 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -599,3 +599,4 @@ region = "eu-central-1" payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" +disputes = "hyperswitch-dispute-events" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index cfe696e42c0..3c971d69f8a 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -213,6 +213,7 @@ region = "eu-central-1" payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" +disputes = "hyperswitch-dispute-events" # This section provides some secret values. [secrets] diff --git a/config/development.toml b/config/development.toml index a7abec7fb74..0878caf3e63 100644 --- a/config/development.toml +++ b/config/development.toml @@ -596,3 +596,4 @@ region = "eu-central-1" payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" +disputes = "hyperswitch-dispute-events" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 4d1731b53ff..6a01c14fdb2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -454,4 +454,5 @@ region = "eu-central-1" [opensearch.indexes] payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" -refunds = "hyperswitch-refund-events" \ No newline at end of file +refunds = "hyperswitch-refund-events" +disputes = "hyperswitch-dispute-events" diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 68ca51a0df0..a325442047e 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -679,6 +679,7 @@ pub struct OpensearchIndexes { pub payment_attempts: String, pub payment_intents: String, pub refunds: String, + pub disputes: String, } #[derive(Clone, Debug, serde::Deserialize)] @@ -700,6 +701,7 @@ impl Default for OpensearchConfig { payment_attempts: "hyperswitch-payment-attempt-events".to_string(), payment_intents: "hyperswitch-payment-intent-events".to_string(), refunds: "hyperswitch-refund-events".to_string(), + disputes: "hyperswitch-dispute-events".to_string(), }, } } diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 8637c9d1105..d9b8433ba63 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -34,6 +34,7 @@ pub fn search_index_to_opensearch_index(index: SearchIndex, config: &OpensearchI SearchIndex::PaymentAttempts => config.payment_attempts.clone(), SearchIndex::PaymentIntents => config.payment_intents.clone(), SearchIndex::Refunds => config.refunds.clone(), + SearchIndex::Disputes => config.disputes.clone(), } } diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index 07223c90660..3a5b3c307e6 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -36,6 +36,7 @@ pub enum SearchIndex { PaymentAttempts, PaymentIntents, Refunds, + Disputes, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
2024-03-13T10:15:27Z
## Description Search APIs for dashboard global search enhancement - adding dispute events index ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context add dispute events index to global-search ## How did you test it? tested locally
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
tested locally
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/analytics/src/lib.rs", "crates/analytics/src/search.rs", "crates/api_models/src/analytics/search.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4067
Bug: [BUG] WASM build is failing ### Bug Description WASM build fails when I run `make euclid-wasm` ### Expected Behavior Build should be completed successfully ### Actual Behavior Build Fails ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. Run `make euclid-wasm` ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index 14d4c6e4c12..08ad127047c 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -2,7 +2,7 @@ use std::{fmt, ops::Deref, str::FromStr}; use masking::{PeekInterface, Strategy, StrongSecret, WithType}; #[cfg(not(target_arch = "wasm32"))] -use router_env::logger; +use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; @@ -52,14 +52,16 @@ impl FromStr for CardNumber { fn from_str(s: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio - let valid_test_cards = match router_env::which() { - router_env::Env::Development | router_env::Env::Sandbox => vec![ - "4000100511112003", - "6000100611111203", - "3000100811111072", - "9000100111111111", - ], - router_env::Env::Production => vec![], + let valid_test_cards = vec![ + "4000100511112003", + "6000100611111203", + "3000100811111072", + "9000100111111111", + ]; + #[cfg(not(target_arch = "wasm32"))] + let valid_test_cards = match router_env_which() { + Env::Development | Env::Sandbox => valid_test_cards, + Env::Production => vec![], }; if luhn::valid(s) || valid_test_cards.contains(&s) { let cc_no_whitespace: String = s.split_whitespace().collect();
2024-03-13T09:43:15Z
## Description <!-- Describe your changes in detail --> Fixed `FromStr` implementation on `CardNumber` to work with wasm related feature configs. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Run `make euclid-wasm` to verify if Wasm build was successful. <img width="1180" alt="Screenshot 2024-03-13 at 3 12 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/480b4373-36ba-401a-a18c-849541c524d7">
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
Run `make euclid-wasm` to verify if Wasm build was successful. <img width="1180" alt="Screenshot 2024-03-13 at 3 12 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/480b4373-36ba-401a-a18c-849541c524d7">
[ "crates/cards/src/validate.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4020
Bug: [REFACTOR] : Setup payment_method_status from trackers to show in payment repsonse ### Feature Description `payment_method` object from DB will be derived in `get_tracker` . We need to set the `payment_method_status` depending upon the derived status for the payments with no `on_session`. ### Possible Implementation `payment_method` object from DB will be derived in `get_tracker` we just need to set that up in `post_update_tracker` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b8a4c5dfc67..7f500eeee21 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2210,7 +2210,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 6e185ea66d8..71f62b1cb79 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 315ddd3b39b..b128c11baff 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, @@ -778,7 +778,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, ))
2024-03-13T07:52:01Z
## Description <!-- Describe your changes in detail --> `payment_method` object from DB will be derived in `get_tracker` . We need to set the `payment_method_status` depending upon the derived status for the payments with no `on_session`. Moreover removing field `payment_method_status` from `PaymentsData` as it is already present in `payment_method_info` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Sample curl: ### `Payment Create` with confirm as false: ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eZdRVkfE8sbYE7JSzm2Tu0HAca0PHRY6u3JoSFBukHuxoYeXw7bgwr7Gy2DJn1kS' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "cus_v6LovN3Zs9k8QQ2UYcbi", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "40", "card_holder_name": "John", "card_cvc": "737" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` `Payment's Confirm` using token ``` curl --location 'http://127.0.0.1:8080/payments/pay_y5QhUc1Z5Y14FYOQ7qcm/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_xxxx' \ --data '{ "payment_token": "token_UCstChJwCzgeWKlPJijf", "card_cvc": "123" }' ``` Response should include these two fields ``` "payment_method_id": "pm_pzFcNslye3gZLxUlmDbg", "payment_method_status": "active" (previously it was null) ``` The possible status and mappings are as follows: ``` AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, AttemptStatus::Failure => Self::Inactive, AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Processing, ```
9878fd90660fb14512e7f26f81b70fc4a1f58aa8
Sample curl: ### `Payment Create` with confirm as false: ``` curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eZdRVkfE8sbYE7JSzm2Tu0HAca0PHRY6u3JoSFBukHuxoYeXw7bgwr7Gy2DJn1kS' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "cus_v6LovN3Zs9k8QQ2UYcbi", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "40", "card_holder_name": "John", "card_cvc": "737" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` `Payment's Confirm` using token ``` curl --location 'http://127.0.0.1:8080/payments/pay_y5QhUc1Z5Y14FYOQ7qcm/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_xxxx' \ --data '{ "payment_token": "token_UCstChJwCzgeWKlPJijf", "card_cvc": "123" }' ``` Response should include these two fields ``` "payment_method_id": "pm_pzFcNslye3gZLxUlmDbg", "payment_method_status": "active" (previously it was null) ``` The possible status and mappings are as follows: ``` AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, AttemptStatus::Failure => Self::Inactive, AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Processing, ```
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_approve.rs", "crates/router/src/core/payments/operations/payment_cancel.rs", "crates/router/src/core/payments/operations/payment_capture.rs", "crates/router/src/core/payments/operations/payment_complete_authorize.rs", ...
juspay/hyperswitch
juspay__hyperswitch-4053
Bug: [REFACTOR] Enable country currency filter for cards ### Feature Description The functionality to process payments for specific countries and currencies is required for certain connectors. This feature should be implemented based on the connector configurations for cards. ### Possible Implementation The configuration filter for country currency on cards must be activated. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 847950d4f45..765eac93f59 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2356,15 +2356,27 @@ fn filter_pm_based_on_config<'a>( .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); - payment_attempt + 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
2024-03-13T07:23:23Z
## Description <!-- Describe your changes in detail --> This PR enables country, currency filter for cards in list payment methods for merchants ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payment Method List needs to be verified for USD and Non-USD payments via BOA: 1. Payments Request(with confirm false): ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "INR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "city": "תל אביב", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "business_label": "food", "business_country": "US" }' ``` Payments Response: ``` { "payment_id": "pay_3ftTdmvei4RVQamsfyfJ", "merchant_id": "merchant_1706697715", "status": "requires_payment_method", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2", "created": "2024-03-13T07:26:39.814Z", "currency": "INR", "customer_id": "CustomerX", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "תל אביב", "country": "US", "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1710314799, "expires": 1710318399, "secret": "epk_35a516b093434ef6a7bff36ae0efd437" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_j9PVFpZYzQU1j7yyjkJJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-13T07:41:39.813Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payment Methods List Request: ``` `curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'` ``` Payment Methods List Response: - For Non-USD Currencies: ``` { "redirect_url": "https://google.com/success", "currency": "INR", "payment_methods": [], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ``` - For USD: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
5c380def254ddc25aa296fa907734f14cf08694b
Payment Method List needs to be verified for USD and Non-USD payments via BOA: 1. Payments Request(with confirm false): ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "INR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "city": "תל אביב", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "business_label": "food", "business_country": "US" }' ``` Payments Response: ``` { "payment_id": "pay_3ftTdmvei4RVQamsfyfJ", "merchant_id": "merchant_1706697715", "status": "requires_payment_method", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2", "created": "2024-03-13T07:26:39.814Z", "currency": "INR", "customer_id": "CustomerX", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "תל אביב", "country": "US", "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1710314799, "expires": 1710318399, "secret": "epk_35a516b093434ef6a7bff36ae0efd437" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_j9PVFpZYzQU1j7yyjkJJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-13T07:41:39.813Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payment Methods List Request: ``` `curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'` ``` Payment Methods List Response: - For Non-USD Currencies: ``` { "redirect_url": "https://google.com/success", "currency": "INR", "payment_methods": [], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ``` - For USD: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4051
Bug: [BUG] 3DS Payments through Complete Authorize flow failing ### Bug Description When doing a 3DS payment that proceeds through the Complete Authorize flow, the token data fetch from Redis fails due to a missing `payment_method` parameter. ### Expected Behavior The token data fetch from Redis should succeed with the correct token and payment method. ### Actual Behavior Currently, the token data fetch fails, because it doesn't receive the payment method in the request, but instead is expected to pick it up from the payment attempt, which it's currently not doing. ### Steps To Reproduce 1. Create a Merchant Account, and a Connector account for any connector that uses Complete Authorize flow for 3DS (like Cybersource) 2. Try to make a 3DS payment. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): `1.71.0` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 4e38294d4dd..0f08d14e439 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -131,8 +131,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> } } - let token_data = if let Some(token) = token.clone() { - Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?) + let token_data = if let Some((token, payment_method)) = token + .as_ref() + .zip(payment_method.or(payment_attempt.payment_method)) + { + Some( + helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method)) + .await?, + ) } else { None };
2024-03-13T07:12:58Z
## Description <!-- Describe your changes in detail --> This PR fixes the issue where token data fetch from Redis was failing for 3DS payments going through the complete authorize flow. The issue being that the payment method was being taken from the request, where it may not be present. The solution was to add the payment method stored in the payment attempt as a fallback. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Certain connectors confirm their payments through the Complete Authorize flow when it comes to 3DS. To ensure that the token data fetch for this flow doesn't fail, we should be using the payment attempt as the fallback ground of truth for any missing data. This PR adds this fallback. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 3DS Payments with Cybersource (failing before, passing now) Payment Confirmation: <img width="962" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/95baacc2-a53b-4181-9c02-c75d6d404f96"> Payment Redirection (Succeeding): <img width="1128" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/429fe3a1-c40d-47f2-abe3-ab8f45f90396">
5c380def254ddc25aa296fa907734f14cf08694b
3DS Payments with Cybersource (failing before, passing now) Payment Confirmation: <img width="962" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/95baacc2-a53b-4181-9c02-c75d6d404f96"> Payment Redirection (Succeeding): <img width="1128" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/429fe3a1-c40d-47f2-abe3-ab8f45f90396">
[ "crates/router/src/core/payments/operations/payment_complete_authorize.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4049
Bug: [BUG] : [Cybersource] Mandate creation condition ### Bug Description Currently mandate gets created if `mandate_data` is passed in the request which is deprecated ### Expected Behavior Create mandate with connector if setup_future_usgae: off_session and customer_acceptance is present ### Actual Behavior Currently mandate gets created if `mandate_data` is passed in the request which is deprecated ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 60ff508d39c..2fd559680ea 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,5 +1,6 @@ use api_models::payments; use base64::Engine; +use common_enums::FutureUsage; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -500,47 +501,54 @@ impl Option<String>, ), ) -> Result<Self, Self::Error> { - let (action_list, action_token_types, authorization_options) = - if item.router_data.request.setup_mandate_details.is_some() { - ( - Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::PaymentInstrument]), - Some(CybersourceAuthorizationOptions { - initiator: Some(CybersourcePaymentInitiator { - initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), - credential_stored_on_file: Some(true), - stored_credential_used: None, - }), - merchant_intitiated_transaction: None, + let (action_list, action_token_types, authorization_options) = if item + .router_data + .request + .setup_future_usage + .map_or(false, |future_usage| { + matches!(future_usage, FutureUsage::OffSession) + }) + && item.router_data.request.customer_acceptance.is_some() + { + ( + Some(vec![CybersourceActionsList::TokenCreate]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), + Some(CybersourceAuthorizationOptions { + initiator: Some(CybersourcePaymentInitiator { + initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), + credential_stored_on_file: Some(true), + stored_credential_used: None, }), - ) - } else if item.router_data.request.connector_mandate_id().is_some() { - let original_amount = item - .router_data - .get_recurring_mandate_payment_data()? - .get_original_payment_amount()?; - let original_currency = item - .router_data - .get_recurring_mandate_payment_data()? - .get_original_payment_currency()?; - ( - None, - None, - Some(CybersourceAuthorizationOptions { - initiator: None, - merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { - reason: None, - original_authorized_amount: Some(utils::get_amount_as_string( - &types::api::CurrencyUnit::Base, - original_amount, - original_currency, - )?), - }), + merchant_intitiated_transaction: None, + }), + ) + } else if item.router_data.request.connector_mandate_id().is_some() { + let original_amount = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_amount()?; + let original_currency = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_currency()?; + ( + None, + None, + Some(CybersourceAuthorizationOptions { + initiator: None, + merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { + reason: None, + original_authorized_amount: Some(utils::get_amount_as_string( + &types::api::CurrencyUnit::Base, + original_amount, + original_currency, + )?), }), - ) - } else { - (None, None, None) - }; + }), + ) + } else { + (None, None, None) + }; let commerce_indicator = match network { Some(card_network) => match card_network.to_lowercase().as_str() { "amex" => "aesk", @@ -581,23 +589,30 @@ impl &CybersourceConsumerAuthValidateResponse, ), ) -> Self { - let (action_list, action_token_types, authorization_options) = - if item.router_data.request.setup_future_usage.is_some() { - ( - Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::PaymentInstrument]), - Some(CybersourceAuthorizationOptions { - initiator: Some(CybersourcePaymentInitiator { - initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), - credential_stored_on_file: Some(true), - stored_credential_used: None, - }), - merchant_intitiated_transaction: None, + let (action_list, action_token_types, authorization_options) = if item + .router_data + .request + .setup_future_usage + .map_or(false, |future_usage| { + matches!(future_usage, FutureUsage::OffSession) + }) + //TODO check for customer acceptance also + { + ( + Some(vec![CybersourceActionsList::TokenCreate]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), + Some(CybersourceAuthorizationOptions { + initiator: Some(CybersourcePaymentInitiator { + initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), + credential_stored_on_file: Some(true), + stored_credential_used: None, }), - ) - } else { - (None, None, None) - }; + merchant_intitiated_transaction: None, + }), + ) + } else { + (None, None, None) + }; Self { capture: Some(matches!( item.router_data.request.capture_method,
2024-03-12T17:00:50Z
## Description <!-- Describe your changes in detail --> Create mandate with connector if `setup_future_usgae: off_session` and `customer_acceptance` is present. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #4049 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a Mandate Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_j23UDZ4X6JcYN6Jz3esn78yIMGYYCEjA3oCBvwogG8vqb8AjGnFGRMezdSkxlJDX' \ --data-raw '{ "amount": 2810, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks5", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4456530000001096", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100" } }, "billing": { "address": { "city": "SanFransico", "country": "AE", "line1": "hdh", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` - Create a recurring Payment ``` curl --location 'http://localhost:8080/payments/pay_7AdU4tNk55yv7dLMEvT7/confirm' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_xsGUpiN8xzYbVBQBfbjRWhFi9JfoppTJZtV6mgwp6w5oG87TD0BLRztSyDlo9pBu' \ --data '{ "payment_token": "token_JZSFn3jCe8usurf8ofcF", "payment_method": "card" }' ```
3eff4ebd3a60b5831cbec0158527475c8f7d7eb4
- Create a Mandate Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_j23UDZ4X6JcYN6Jz3esn78yIMGYYCEjA3oCBvwogG8vqb8AjGnFGRMezdSkxlJDX' \ --data-raw '{ "amount": 2810, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks5", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4456530000001096", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100" } }, "billing": { "address": { "city": "SanFransico", "country": "AE", "line1": "hdh", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` - Create a recurring Payment ``` curl --location 'http://localhost:8080/payments/pay_7AdU4tNk55yv7dLMEvT7/confirm' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_xsGUpiN8xzYbVBQBfbjRWhFi9JfoppTJZtV6mgwp6w5oG87TD0BLRztSyDlo9pBu' \ --data '{ "payment_token": "token_JZSFn3jCe8usurf8ofcF", "payment_method": "card" }' ```
[ "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4047
Bug: [BUG] : [Adyen] Production URL endpoint ### Bug Description For Adyen production URL endpoint is not correctly configured as compared to how it is used ### Expected Behavior `/` is missing in the end for production endpoint ### Actual Behavior For Adyen production URL endpoint is not correctly configured as compared to how it is used ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 892f11e9415..a6a37858308 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -17,7 +17,7 @@ payout_connector_list = "wise" [connectors] aci.base_url = "https://eu-test.oppwa.com/" -adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout" +adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout/" adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 67e319ddc22..d79761da472 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -1761,7 +1761,7 @@ impl api::IncomingWebhook for Adyen { } if adyen::is_refund_event(&notif.event_code) { return Ok(api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::ConnectorRefundId(notif.psp_reference), + api_models::webhooks::RefundIdType::RefundId(notif.merchant_reference), )); } if adyen::is_chargeback_event(&notif.event_code) { diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 1eede78503b..cff6c7a8d99 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1128,6 +1128,7 @@ pub struct AdyenCard { expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Option<Secret<String>>, + holder_name: Option<Secret<String>>, brand: Option<CardBrand>, //Mandatory for mandate using network_txns_id network_payment_reference: Option<Secret<String>>, } @@ -1980,6 +1981,7 @@ impl<'a> TryFrom<&api::Card> for AdyenPaymentMethod<'a> { expiry_month: card.card_exp_month.clone(), expiry_year: card.get_expiry_year_4_digit(), cvc: Some(card.card_cvc.clone()), + holder_name: card.card_holder_name.clone(), brand: None, network_payment_reference: None, }; @@ -2584,6 +2586,7 @@ impl<'a> expiry_month: card.card_exp_month.clone(), expiry_year: card.card_exp_year.clone(), cvc: None, + holder_name: card.card_holder_name.clone(), brand: Some(brand), network_payment_reference: Some(Secret::new(network_mandate_id)), };
2024-03-12T12:58:21Z
## Description <!-- Describe your changes in detail --> - Update Prod URL endpoint - Handle refunds webhooks using hyperswitch internal refund id - Add card holder name ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [X] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> Updated Prod URL endpoint ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #4047 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Trigger a refunds transaction ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \ --data '{ "payment_id": "pay_ow2YSNvgVDZlGTv3o8wc", "reason": "RETURN", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Check for outgoing webhook and also retrieve the refund to confirm the Status change ![Screenshot 2024-03-12 at 6 31 39 PM](https://github.com/juspay/hyperswitch/assets/55536657/b6195d05-7972-4079-b1f6-bdeee1fb1f2f) - Send card holder name in the cards request it should be visible in Adyen Dashboard for the payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_8Ix85cVgHD3x4DQIFZTV", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "This is me making a statement", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ```
708cce926125a29b406db48cf0ebd35b217927d4
- Trigger a refunds transaction ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \ --data '{ "payment_id": "pay_ow2YSNvgVDZlGTv3o8wc", "reason": "RETURN", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Check for outgoing webhook and also retrieve the refund to confirm the Status change ![Screenshot 2024-03-12 at 6 31 39 PM](https://github.com/juspay/hyperswitch/assets/55536657/b6195d05-7972-4079-b1f6-bdeee1fb1f2f) - Send card holder name in the cards request it should be visible in Adyen Dashboard for the payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_8Ix85cVgHD3x4DQIFZTV", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "This is me making a statement", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ```
[ "config/deployments/production.toml", "crates/router/src/connector/adyen.rs", "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3891
Bug: Generate and publish Open API specs
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 33d355d255a..dd0c5e4b05c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -354,6 +354,7 @@ pub struct PaymentsRequest { pub mandate_data: Option<MandateData>, /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs index 6011621fc13..6a6f41d98cd 100644 --- a/crates/openapi/src/routes/customers.rs +++ b/crates/openapi/src/routes/customers.rs @@ -124,7 +124,8 @@ pub async fn customers_mandates_list() {} get, path = "/{customer_id}/payment_methods/{payment_method_id}/default", params ( - ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"), + ("customer_id" = String,Path, description ="The unique identifier for the Customer"), + ("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"), ), responses( (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ), diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 12fc7778a31..20d87b91e79 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -100,6 +100,14 @@ "currency": "USD" } } + }, + "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" + } } }) ) @@ -302,6 +310,14 @@ pub fn payments_update() {} "card_holder_name": "joseph Doe", "card_cvc": "123" } + }, + "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" + } } } ) diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 66007b69342..940218acf31 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -2606,6 +2606,14 @@ "authentication_type": "no_three_ds", "confirm": true, "currency": "USD", + "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" + } + }, "customer_id": "StripeCustomer123", "mandate_data": { "customer_acceptance": { @@ -3153,6 +3161,14 @@ "examples": { "Confirm a payment with payment method data": { "value": { + "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" + } + }, "payment_method": "card", "payment_method_data": { "card": { @@ -4208,9 +4224,18 @@ "operationId": "Set the Payment Method as Default", "parameters": [ { - "name": "method_id", + "name": "customer_id", "in": "path", - "description": "Set the Payment Method as Default for the Customer", + "description": "The unique identifier for the Customer", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "payment_method_id", + "in": "path", + "description": "The unique identifier for the Payment Method", "required": true, "schema": { "type": "string"
2024-03-12T09:57:46Z
## Description update open-api spec to have payment changes ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
ac8ddd40208f3da5f65ca97bf5033cea5ca3ebe3
[ "crates/api_models/src/payments.rs", "crates/openapi/src/routes/customers.rs", "crates/openapi/src/routes/payments.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-3991
Bug: Store Network Reference ID against the Payment Method ID for all off-session payments During the CIT there needs to be a validation which check for the `setup_future_usage` field, if it is set to `off_session` the NRID returned from the connector needs to be stored against the particular `payment_method_id` in the `network_transaction_id` column of the `payment_methods` table.
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 7e8dcb639c3..7c28f4cd281 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -126,6 +126,10 @@ pub enum PaymentMethodUpdate { LastUsedUpdate { last_used_at: PrimitiveDateTime, }, + NetworkTransactionIdAndStatusUpdate { + network_transaction_id: Option<String>, + status: Option<storage_enums::PaymentMethodStatus>, + }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, @@ -140,6 +144,7 @@ pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, + network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, connector_mandate_details: Option<serde_json::Value>, } @@ -159,6 +164,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { metadata, payment_method_data: None, last_used_at: None, + network_transaction_id: None, status: None, connector_mandate_details: None, }, @@ -168,6 +174,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { metadata: None, payment_method_data, last_used_at: None, + network_transaction_id: None, status: None, connector_mandate_details: None, }, @@ -175,13 +182,26 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { metadata: None, payment_method_data: None, last_used_at: Some(last_used_at), + network_transaction_id: None, status: None, connector_mandate_details: None, }, + PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { + network_transaction_id, + status, + } => Self { + metadata: None, + payment_method_data: None, + last_used_at: None, + network_transaction_id, + status, + connector_mandate_details: None, + }, PaymentMethodUpdate::StatusUpdate { status } => Self { metadata: None, payment_method_data: None, last_used_at: None, + network_transaction_id: None, status, connector_mandate_details: None, }, @@ -193,6 +213,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { last_used_at: None, status: None, connector_mandate_details, + network_transaction_id: None, }, } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 7edf28f2c38..45aeb1e9074 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2231,6 +2231,7 @@ impl Deref for PaymentIntentSyncResponse { pub struct StripeAdditionalCardDetails { checks: Option<Value>, three_d_secure: Option<Value>, + network_transaction_id: Option<String>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] @@ -2685,12 +2686,24 @@ impl<F, T> item.response.id.clone(), )) } else { + let network_transaction_id = match item.response.latest_attempt { + Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt + .payment_method_details + .and_then(|payment_method_details| match payment_method_details { + StripePaymentMethodDetailsResponse::Card { card } => { + card.network_transaction_id + } + _ => None, + }), + _ => None, + }; + Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference, connector_metadata: None, - network_txn_id: Option::foreign_from(item.response.latest_attempt), + network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, }) @@ -3140,6 +3153,7 @@ pub struct LatestPaymentAttempt { pub payment_method_options: Option<StripePaymentMethodOptions>, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } + // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 64346a94a9d..d94864c75b5 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -87,6 +87,7 @@ pub async fn create_payment_method( payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, connector_mandate_details: Option<serde_json::Value>, + network_transaction_id: Option<String>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { let customer = db .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) @@ -107,6 +108,7 @@ pub async fn create_payment_method( payment_method_data, connector_mandate_details, customer_acceptance: customer_acceptance.map(masking::Secret::new), + network_transaction_id: network_transaction_id.to_owned(), ..storage::PaymentMethodNew::default() }) .await @@ -205,6 +207,7 @@ pub async fn get_or_insert_payment_method( None, locker_id, None, + None, ) .await } else { @@ -392,6 +395,7 @@ pub async fn add_payment_method( None, locker_id, None, + None, ) .await?; } @@ -412,6 +416,7 @@ pub async fn insert_payment_method( customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, + network_transaction_id: Option<String>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card @@ -430,6 +435,7 @@ pub async fn insert_payment_method( pm_data_encrypted, key_store, connector_mandate_details, + network_transaction_id, ) .await } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 66f35e63b2c..f418b660380 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -7,7 +7,7 @@ use data_models::payments::payment_attempt::PaymentAttempt; use error_stack::{report, ResultExt}; use futures::FutureExt; use router_derive; -use router_env::{instrument, tracing}; +use router_env::{instrument, logger, tracing}; use storage_impl::DataModelExt; use tracing_futures::Instrument; @@ -34,7 +34,7 @@ use crate::{ self, api, storage::{self, enums}, transformers::{ForeignFrom, ForeignTryFrom}, - CaptureSyncResponse, + CaptureSyncResponse, ErrorResponse, }, utils, }; @@ -833,7 +833,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; let amount_captured = get_total_amount_captured( - router_data.request, + &router_data.request, router_data.amount_captured, router_data.status, &payment_data, @@ -862,7 +862,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }, }; - update_payment_method_status(state, &mut payment_data, router_data.status).await?; + update_payment_method_status_and_ntid( + state, + &mut payment_data, + router_data.status, + router_data.response.clone(), + ) + .await?; let m_db = state.clone().store; let m_payment_data_payment_intent = payment_data.payment_intent.clone(); let m_payment_intent_update = payment_intent_update.clone(); @@ -954,10 +960,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( Ok(payment_data) } -async fn update_payment_method_status<F: Clone>( +async fn update_payment_method_status_and_ntid<F: Clone>( state: &AppState, payment_data: &mut PaymentData<F>, attempt_status: common_enums::AttemptStatus, + payment_response: Result<types::PaymentsResponseData, ErrorResponse>, ) -> RouterResult<()> { if let Some(id) = &payment_data.payment_attempt.payment_method_id { let pm = state @@ -965,8 +972,20 @@ async fn update_payment_method_status<F: Clone>( .find_payment_method(id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + let network_transaction_id = payment_response + .map(|resp| match resp { + crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { + network_txn_id.to_owned() + } + _ => None, + }) + .map_err(|err| { + logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); + }) + .ok() + .flatten(); - if pm.status != common_enums::PaymentMethodStatus::Active + let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active && pm.status != attempt_status.into() { let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status); @@ -975,16 +994,23 @@ async fn update_payment_method_status<F: Clone>( .payment_method_info .as_mut() .map(|info| info.status = updated_pm_status); - let pm_update = storage::PaymentMethodUpdate::StatusUpdate { + storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { + network_transaction_id, status: Some(updated_pm_status), - }; - state - .store - .update_payment_method(pm, pm_update) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to update payment method in db")?; - } + } + } else { + storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { + network_transaction_id, + status: None, + } + }; + + state + .store + .update_payment_method(pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")?; }; Ok(()) } @@ -1043,7 +1069,7 @@ fn get_capture_update_for_unmapped_capture_responses( } fn get_total_amount_captured<F: Clone, T: types::Capturable>( - request: T, + request: &T, amount_captured: Option<i64>, router_data_status: enums::AttemptStatus, payment_data: &PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 4d616146908..7a8f487d73a 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -399,6 +399,18 @@ async fn get_tracker_for_sync< .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; + let payment_method_info = + if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { + Some( + db.find_payment_method(payment_method_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + .attach_printable("error retrieving payment method from DB")?, + ) + } else { + None + }; + 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( @@ -436,7 +448,7 @@ async fn get_tracker_for_sync< token_data: None, confirm: Some(request.force_sync), payment_method_data: None, - payment_method_info: None, + payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(&payment_attempt.status) diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 3941fad5a42..47cd1cd9eb7 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -57,6 +57,13 @@ where .map(|token_filter| token_filter.long_lived_token) .unwrap_or(false); + let network_transaction_id = match responses.clone() { + types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { + network_txn_id + } + _ => None, + }; + let connector_token = if token_store { let tokens = resp .payment_method_token @@ -255,6 +262,7 @@ where pm_data_encrypted, key_store, connector_mandate_details, + network_transaction_id, ) .await } else { @@ -337,6 +345,7 @@ where customer_acceptance, locker_id, connector_mandate_details, + network_transaction_id, ) .await } else { @@ -459,6 +468,7 @@ where pm_data_encrypted, key_store, connector_mandate_details, + network_transaction_id, ) .await?; } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 1a94186a86f..6efe6ee9a77 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -13,8 +13,8 @@ use crate::{ core::{ errors::{self, RouterResult}, payment_methods::{ - cards, transformers, - transformers::{StoreCardReq, StoreGenericReq, StoreLockerReq}, + cards, + transformers::{self, StoreCardReq, StoreGenericReq, StoreLockerReq}, vault, }, payments::{ @@ -389,6 +389,7 @@ pub async fn save_payout_data_to_locker( card_details_encrypted, key_store, None, + None, ) .await?;
2024-03-12T08:10:34Z
## Description <!-- Describe your changes in detail --> During the CIT there needs to be a validation which check for the setup_future_usage field, if it is set to off_session the NRID returned from the connector needs to be stored against the particular payment_method_id in the network_transaction_id column of the payment_methods table. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create a Merchant account Create a mca for stripe, adyen or cybersource Create a mandate payment (Setup mandate) ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` Once the mandate is successful the network_transaction_id is stored as below `network_transaction_id` being stored in `payment_method` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ddaed1ec-1b75-4d29-b889-c3e3cedaa62d)
ad1f74f2c3da9e2a40e8646d8af07081e7ac3ee1
Create a Merchant account Create a mca for stripe, adyen or cybersource Create a mandate payment (Setup mandate) ``` { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` Once the mandate is successful the network_transaction_id is stored as below `network_transaction_id` being stored in `payment_method` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ddaed1ec-1b75-4d29-b889-c3e3cedaa62d)
[ "crates/diesel_models/src/payment_method.rs", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/operations/payment_status.rs", "crates/router/src/core/p...
juspay/hyperswitch
juspay__hyperswitch-4037
Bug: Filter wallet payment method from mca based on customer pm https://github.com/juspay/hyperswitch/issues/3741 Apple pay wallet is getting filtered out from list merchant payment method if the customer has saved it already. This has to be done for all wallets
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index fccacfef45d..985ddcfe849 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1344,42 +1344,50 @@ pub async fn list_payment_methods( .await?; } - // Filter out applepay payment method from mca if customer has already saved it - response - .iter() - .position(|pm| { - pm.payment_method == enums::PaymentMethod::Wallet - && pm.payment_method_type == enums::PaymentMethodType::ApplePay - }) + // Filter out wallet payment method from mca if customer has already saved it + customer .as_ref() - .zip(customer.as_ref()) - .async_map(|(index, customer)| async { - match db - .find_payment_method_by_customer_id_merchant_id_list( - &customer.customer_id, - &merchant_account.merchant_id, - None, - ) - .await - { - Ok(customer_payment_methods) => { - if customer_payment_methods.iter().any(|pm| { - pm.payment_method == enums::PaymentMethod::Wallet - && pm.payment_method_type == Some(enums::PaymentMethodType::ApplePay) - }) { - response.remove(*index); - } - Ok(()) - } - Err(error) => { - if error.current_context().is_db_not_found() { + .async_map(|customer| async { + let wallet_pm_exists = response + .iter() + .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet); + if wallet_pm_exists { + match db + .find_payment_method_by_customer_id_merchant_id_list( + &customer.customer_id, + &merchant_account.merchant_id, + None, + ) + .await + { + Ok(customer_payment_methods) => { + let customer_wallet_pm = customer_payment_methods + .iter() + .filter(|cust_pm| { + cust_pm.payment_method == enums::PaymentMethod::Wallet + }) + .collect::<Vec<_>>(); + + response.retain(|mca| { + !(mca.payment_method == enums::PaymentMethod::Wallet + && customer_wallet_pm.iter().any(|cust_pm| { + cust_pm.payment_method_type == Some(mca.payment_method_type) + })) + }); Ok(()) - } else { - Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to find payment methods for a customer") + } + Err(error) => { + if error.current_context().is_db_not_found() { + Ok(()) + } else { + Err(error) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to find payment methods for a customer") + } } } + } else { + Ok(()) } }) .await
2024-03-11T16:56:04Z
## Description <!-- Describe your changes in detail --> https://github.com/juspay/hyperswitch/pull/3953 Similar to above issue but now the PR refactors to filter out any wallet payment method from mca if it is saved by a customer ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay or googlepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. The payment method which u saved earlier shoudn't be listed in the result 7. Check with saving both google_pay and apple_pay to customer (In this case both has to be filtered when done list mca)
e87f2ea8c5669473940df8bc2f5c61fdf3f218ff
1. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay or googlepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. The payment method which u saved earlier shoudn't be listed in the result 7. Check with saving both google_pay and apple_pay to customer (In this case both has to be filtered when done list mca)
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4036
Bug: [BUG] [AUTHORIZEDOTNET] Connector Audit ### Bug Description Authorizedotnet Connector Audit fixes. 1. Production endpoint is wrong 2. Connector Transaction ID is not passed in 2XX Error Response 3. Default case handling in code ### Expected Behavior Authorizedotnet Connector Audit fixes. 1. Production endpoint should be https://api.authorize.net/xml/v1/request.api. 2. Connector Transaction ID should be passed to 2XX Error Response. 3. Default case handling should not be present in code. ### Actual Behavior Authorizedotnet Connector Audit fixes. 1. Production endpoint is wrong 2. Connector Transaction ID is not passed in 2XX Error Response 3. Default case handling in code ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 892f11e9415..6bfcad3ad50 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -21,7 +21,7 @@ adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpaymen adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" -authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" +authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/" bitpay.base_url = "https://bitpay.com" diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 0aba48fa5e5..be02b4524f8 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -685,8 +685,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let intermediate_response = bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes()); - let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response - .parse_struct("AuthorizedotnetSyncResponse") + let response: authorizedotnet::AuthorizedotnetRSyncResponse = intermediate_response + .parse_struct("AuthorizedotnetRSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -872,11 +872,17 @@ impl api::IncomingWebhook for Authorizedotnet { ), )) } - _ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - authorizedotnet::get_trans_id(&details)?, - ), - )), + authorizedotnet::AuthorizedotnetWebhookEvent::AuthorizationCreated + | authorizedotnet::AuthorizedotnetWebhookEvent::PriorAuthCapture + | authorizedotnet::AuthorizedotnetWebhookEvent::AuthCapCreated + | authorizedotnet::AuthorizedotnetWebhookEvent::CaptureCreated + | authorizedotnet::AuthorizedotnetWebhookEvent::VoidCreated => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + authorizedotnet::get_trans_id(&details)?, + ), + )) + } } } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 5d3a7d0054f..4a79b179b84 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -190,44 +190,48 @@ fn get_pm_and_subsequent_auth_detail( } } } - _ => match item.router_data.request.payment_method_data { - api::PaymentMethodData::Card(ref ccard) => { - Ok(( - PaymentDetails::CreditCard(CreditCardDetails { - card_number: (*ccard.card_number).clone(), - // expiration_date: format!("{expiry_year}-{expiry_month}").into(), - expiration_date: ccard.get_expiry_date_as_yyyymm("-"), - card_code: Some(ccard.card_cvc.clone()), - }), - Some(ProcessingOptions { - is_subsequent_auth: true, - }), + Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => { + match item.router_data.request.payment_method_data { + api::PaymentMethodData::Card(ref ccard) => { + Ok(( + PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + // expiration_date: format!("{expiry_year}-{expiry_month}").into(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: Some(ccard.card_cvc.clone()), + }), + Some(ProcessingOptions { + is_subsequent_auth: true, + }), + None, + )) + } + api::PaymentMethodData::Wallet(ref wallet_data) => Ok(( + get_wallet_data( + wallet_data, + &item.router_data.request.complete_authorize_url, + )?, + None, None, - )) + )), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("authorizedotnet"), + ))? + } } - api::PaymentMethodData::Wallet(ref wallet_data) => Ok(( - get_wallet_data( - wallet_data, - &item.router_data.request.complete_authorize_url, - )?, - None, - None, - )), - api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::PayLater(_) - | api::PaymentMethodData::BankRedirect(_) - | api::PaymentMethodData::BankDebit(_) - | api::PaymentMethodData::BankTransfer(_) - | api::PaymentMethodData::Crypto(_) - | api::PaymentMethodData::MandatePayment - | api::PaymentMethodData::Reward - | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("authorizedotnet"), - ))?, - }, + } } } @@ -382,7 +386,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> country: address.country, }); let transaction_request = TransactionRequest { - transaction_type: TransactionType::from(item.router_data.request.capture_method), + transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency.to_string(), payment: payment_details, @@ -662,7 +666,7 @@ impl<F, T> reason: None, status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(transaction_response.transaction_id.clone()), }) }); let metadata = transaction_response @@ -740,7 +744,7 @@ impl<F, T> reason: None, status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(transaction_response.transaction_id.clone()), }) }); let metadata = transaction_response @@ -886,7 +890,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundRespons reason: None, status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(transaction_response.transaction_id.clone()), }) }); @@ -976,6 +980,15 @@ pub enum SyncStatus { FDSPendingReview, } +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum RSyncStatus { + RefundSettledSuccessfully, + RefundPendingSettlement, + Declined, + GeneralError, +} + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SyncTransactionResponse { @@ -990,14 +1003,18 @@ pub struct AuthorizedotnetSyncResponse { messages: ResponseMessages, } -impl From<SyncStatus> for enums::RefundStatus { - fn from(transaction_status: SyncStatus) -> Self { - match transaction_status { - SyncStatus::RefundSettledSuccessfully => Self::Success, - SyncStatus::RefundPendingSettlement => Self::Pending, - _ => Self::Failure, - } - } +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RSyncTransactionResponse { + #[serde(rename = "transId")] + transaction_id: String, + transaction_status: RSyncStatus, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AuthorizedotnetRSyncResponse { + transaction: Option<RSyncTransactionResponse>, + messages: ResponseMessages, } impl From<SyncStatus> for enums::AttemptStatus { @@ -1017,13 +1034,23 @@ impl From<SyncStatus> for enums::AttemptStatus { } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>> +impl From<RSyncStatus> for enums::RefundStatus { + fn from(transaction_status: RSyncStatus) -> Self { + match transaction_status { + RSyncStatus::RefundSettledSuccessfully => Self::Success, + RSyncStatus::RefundPendingSettlement => Self::Pending, + RSyncStatus::Declined | RSyncStatus::GeneralError => Self::Failure, + } + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>> for types::RefundsRouterData<api::RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>, + item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>, ) -> Result<Self, Self::Error> { match item.response.transaction { Some(transaction) => { @@ -1108,11 +1135,24 @@ fn construct_refund_payment_details(masked_number: String) -> PaymentDetails { }) } -impl From<Option<enums::CaptureMethod>> for TransactionType { - fn from(capture_method: Option<enums::CaptureMethod>) -> Self { +impl TryFrom<Option<enums::CaptureMethod>> for TransactionType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> { match capture_method { - Some(enums::CaptureMethod::Manual) => Self::Authorization, - _ => Self::Payment, + Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization), + Some(enums::CaptureMethod::Automatic) | None => Ok(Self::Payment), + Some(enums::CaptureMethod::ManualMultiple) => { + Err(utils::construct_not_supported_error_report( + enums::CaptureMethod::ManualMultiple, + "authorizedotnet", + ))? + } + Some(enums::CaptureMethod::Scheduled) => { + Err(utils::construct_not_supported_error_report( + enums::CaptureMethod::Scheduled, + "authorizedotnet", + ))? + } } } } @@ -1359,9 +1399,19 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterD .change_context(errors::ConnectorError::ResponseDeserializationFailed)? .payer_id; let transaction_type = match item.router_data.request.capture_method { - Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization, - _ => TransactionType::ContinueCapture, - }; + Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization), + Some(enums::CaptureMethod::Automatic) | None => Ok(TransactionType::ContinueCapture), + Some(enums::CaptureMethod::ManualMultiple) => { + Err(errors::ConnectorError::NotSupported { + message: enums::CaptureMethod::ManualMultiple.to_string(), + connector: "authorizedotnet", + }) + } + Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported { + message: enums::CaptureMethod::Scheduled.to_string(), + connector: "authorizedotnet", + }), + }?; let transaction_request = TransactionConfirmRequest { transaction_type, payment: PaypalPaymentConfirm {
2024-03-11T13:26:12Z
## Description <!-- Describe your changes in detail --> Authorizedotnet Connector Audit fixes: 1. Production endpoint fixed. 2. Connector Transaction ID added to 2XX Error Response 3. Default case handling removed ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 4. `crates/router/src/configs` 5. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4036 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing needs to be done by creating a 2XX error for a payment via authorizedotnet. 2XX error can be generated by doing 2 back to back transactions with same request body which will trigger a dupliacte transaction error at connector end. Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5WytrFNU7ci62yt6DYvmVVcyVdMG6s92tlbiS9vWLsWgdud2qIDqvPhvfquNza5X' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` Failure Response: ```json { "payment_id": "pay_2LFVZlFX0KHdneXkkZSp", "merchant_id": "merchant_1709720492", "status": "failed", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_2LFVZlFX0KHdneXkkZSp_secret_34pXGRBkphSF4qARev7i", "created": "2024-03-11T13:54:27.251Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "11", "error_message": "A duplicate transaction has been submitted.", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710165267, "expires": 1710168867, "secret": "epk_e39c6817cc0c4abdb7cb8081cf601417" }, "manual_retry_allowed": true, "connector_transaction_id": "0", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-11T14:09:27.251Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now check in DB whether connector_transaction_id is getting populated for the failure scenario: <img width="435" alt="Screenshot 2024-03-11 at 7 30 05 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/42843ae3-cc0e-4323-81a5-641c4dc38d5b">
ce3625cb0cdccc750a073c012f0e541b014c3190
Testing needs to be done by creating a 2XX error for a payment via authorizedotnet. 2XX error can be generated by doing 2 back to back transactions with same request body which will trigger a dupliacte transaction error at connector end. Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5WytrFNU7ci62yt6DYvmVVcyVdMG6s92tlbiS9vWLsWgdud2qIDqvPhvfquNza5X' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` Failure Response: ```json { "payment_id": "pay_2LFVZlFX0KHdneXkkZSp", "merchant_id": "merchant_1709720492", "status": "failed", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_2LFVZlFX0KHdneXkkZSp_secret_34pXGRBkphSF4qARev7i", "created": "2024-03-11T13:54:27.251Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "11", "error_message": "A duplicate transaction has been submitted.", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1710165267, "expires": 1710168867, "secret": "epk_e39c6817cc0c4abdb7cb8081cf601417" }, "manual_retry_allowed": true, "connector_transaction_id": "0", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-11T14:09:27.251Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` Now check in DB whether connector_transaction_id is getting populated for the failure scenario: <img width="435" alt="Screenshot 2024-03-11 at 7 30 05 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/42843ae3-cc0e-4323-81a5-641c4dc38d5b">
[ "config/deployments/production.toml", "crates/router/src/connector/authorizedotnet.rs", "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4033
Bug: [FEATURE] Integrate Plaid as an Open Banking Payment connector ### Feature Description Integrate Plaid as an Open Banking Payment connector. Pre-requisite would be the Open Banking payments core Integration - #3612 ### Possible Implementation Similar to regular connector integration ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 2ffb69c3e3d..eab5e84df9c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -206,6 +206,7 @@ payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" +plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/config/development.toml b/config/development.toml index 6d4914af8b4..827fd71e452 100644 --- a/config/development.toml +++ b/config/development.toml @@ -127,6 +127,7 @@ cards = [ "paypal", "payu", "placetopay", + "plaid", "powertranz", "prophetpay", "shift4", @@ -201,6 +202,7 @@ payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" +plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" @@ -581,4 +583,7 @@ enabled = true file_storage_backend = "file_system" [unmasked_headers] -keys = "user-agent" \ No newline at end of file +keys = "user-agent" + +[locker_open_banking_connectors] +connector_list = [] \ No newline at end of file diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2f94d69790b..91f8480056e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -140,6 +140,7 @@ payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" +plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" @@ -206,6 +207,7 @@ cards = [ "paypal", "payu", "placetopay", + "plaid", "powertranz", "prophetpay", "shift4", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index bf88eca0a0e..067f69b56e1 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -479,6 +479,32 @@ pub struct MerchantConnectorCreate { pub status: Option<api_enums::ConnectorStatus>, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub enum MerchantAccountData { + Iban { + iban: Secret<String>, + name: String, + }, + Bacs { + account_number: Secret<String>, + sort_code: Secret<String>, + name: String, + }, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub enum MerchantRecipientData { + RecipientId(Secret<String>), + WalletId(Secret<String>), + AccountData(MerchantAccountData), +} +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct OpenBankingAuthType { + pub api_key: Secret<String>, + pub key1: Secret<String>, + pub merchant_data: MerchantRecipientData, +} + // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] @@ -505,6 +531,11 @@ pub enum ConnectorAuthType { CurrencyAuthKey { auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, }, + OpenBankingAuth { + api_key: Secret<String>, + key1: Secret<String>, + merchant_data: MerchantRecipientData, + }, #[default] NoKey, } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index dee5f2d0757..a21d03aba90 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1346,6 +1346,7 @@ impl GetPaymentMethodType for BankRedirectData { Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } + Self::OpenBanking { .. } => api_enums::PaymentMethodType::OpenBanking, } } } @@ -1620,6 +1621,7 @@ pub enum BankRedirectData { #[schema(value_type = BankNames)] issuer: api_enums::BankNames, }, + OpenBanking {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -2263,7 +2265,9 @@ pub enum NextActionData { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response - ThirdPartySdkSessionToken { session_token: Option<SessionToken> }, + ThirdPartySdkSessionToken { + session_token: Option<SessionTokenType>, + }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] @@ -3319,6 +3323,13 @@ pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(untagged)] +pub enum SessionTokenType { + Wallet(SessionToken), + OpenBanking(OpenBankingSessionToken), +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] @@ -3390,6 +3401,13 @@ pub struct PaypalSessionTokenResponse { pub session_token: String, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct OpenBankingSessionToken { + /// The session token for OpenBanking Connectors + pub open_banking_session_token: String, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { @@ -3523,7 +3541,7 @@ pub struct PaymentsSessionResponse { #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object - pub session_token: Vec<SessionToken>, + pub session_token: Vec<SessionTokenType>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 9cf138ed330..58c0152d8db 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -163,6 +163,7 @@ pub enum RoutableConnectors { Worldline, Worldpay, Zen, + Plaid, } impl AttemptStatus { @@ -1345,6 +1346,7 @@ pub enum PaymentMethodType { FamilyMart, Seicomart, PayEasy, + OpenBanking, } /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 63abfdb3f73..86ec6d3a709 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1873,6 +1873,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::FamilyMart => Self::Voucher, PaymentMethodType::Seicomart => Self::Voucher, PaymentMethodType::PayEasy => Self::Voucher, + PaymentMethodType::OpenBanking => Self::BankRedirect, } } } diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 0b71f916d03..982ae4a3c43 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -154,6 +154,7 @@ pub enum BankRedirectType { OpenBankingUk, Przelewy24, Trustly, + OpenBanking, } #[derive( Clone, diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index b1f03e8dd55..d09e0cf7f7c 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -159,6 +159,7 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { enums::BankRedirectType::OpenBankingUk => Self::OpenBankingUk, enums::BankRedirectType::Przelewy24 => Self::Przelewy24, enums::BankRedirectType::Trustly => Self::Trustly, + enums::BankRedirectType::OpenBanking => Self::OpenBanking, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index c99b39e36f4..d2f1a752734 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -164,6 +164,9 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::CardRedirect => { Ok(dirval!(CardRedirectType = CardRedirect)) } + global_enums::PaymentMethodType::OpenBanking => { + Ok(dirval!(BankRedirectType = OpenBanking)) + } } } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 5bcb64fd875..00834f8b840 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -283,6 +283,9 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::CardRedirect => { Ok(dirval!(CardRedirectType = CardRedirect)) } + api_enums::PaymentMethodType::OpenBanking => { + Ok(dirval!(BankRedirectType = OpenBanking)) + } } } } diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs index dfcfbb7eddc..1b8568a1e7e 100644 --- a/crates/pm_auth/src/connector/plaid.rs +++ b/crates/pm_auth/src/connector/plaid.rs @@ -15,7 +15,9 @@ use crate::{ types::{ self as auth_types, api::{ - auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken}, + auth_service::{ + self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate, + }, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, }, }, @@ -89,6 +91,8 @@ impl ConnectorCommon for Plaid { } impl auth_service::AuthService for Plaid {} +impl auth_service::PaymentInitiationRecipientCreate for Plaid {} +impl auth_service::PaymentInitiation for Plaid {} impl auth_service::AuthServiceLinkToken for Plaid {} impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> @@ -338,3 +342,89 @@ impl self.build_error_response(res) } } + +impl + ConnectorIntegration< + RecipientCreate, + auth_types::RecipientCreateRequest, + auth_types::RecipientCreateResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, 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: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/payment_initiation/recipient/create" + )) + } + + fn get_request_body( + &self, + req: &auth_types::RecipientCreateRouterData, + ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { + let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentInitiationRecipientCreateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers( + auth_types::PaymentInitiationRecipientCreateType::get_headers( + self, req, connectors, + )?, + ) + .set_body( + auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?, + ) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::RecipientCreateRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> { + let response: plaid::PlaidRecipientCreateResponse = res + .response + .parse_struct("PlaidRecipientCreateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::RecipientCreateRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 5e1ad67aead..c4e018663f4 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -112,6 +112,105 @@ impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { } } +#[derive(Debug, Serialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateRequest { + pub name: String, + #[serde(flatten)] + pub account_data: PlaidRecipientAccountData, + pub address: Option<PlaidRecipientCreateAddress>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateResponse { + pub recipient_id: String, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PlaidRecipientAccountData { + Iban(Secret<String>), + Bacs { + sort_code: Secret<String>, + account: Secret<String>, + }, +} + +impl From<&types::RecipientAccountData> for PlaidRecipientAccountData { + fn from(item: &types::RecipientAccountData) -> Self { + match item { + types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()), + types::RecipientAccountData::Bacs { + sort_code, + account_number, + } => Self::Bacs { + sort_code: sort_code.clone(), + account: account_number.clone(), + }, + } + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateAddress { + pub street: String, + pub city: String, + pub postal_code: String, + pub country: String, +} + +impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress { + fn from(item: &types::RecipientCreateAddress) -> Self { + Self { + street: item.street.clone(), + city: item.city.clone(), + postal_code: item.postal_code.clone(), + country: common_enums::CountryAlpha2::to_string(&item.country), + } + } +} + +impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> { + Ok(Self { + name: item.request.name.clone(), + account_data: PlaidRecipientAccountData::from(&item.request.account_data), + address: item + .request + .address + .as_ref() + .map(PlaidRecipientCreateAddress::from), + }) + } +} + +impl<F, T> + TryFrom< + types::ResponseRouterData< + F, + PlaidRecipientCreateResponse, + T, + types::RecipientCreateResponse, + >, + > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PlaidRecipientCreateResponse, + T, + types::RecipientCreateResponse, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RecipientCreateResponse { + recipient_id: item.response.recipient_id, + }), + ..item.data + }) + } +} #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidBankAccountCredentialsRequest { @@ -269,6 +368,7 @@ impl<F, T> pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, + pub merchant_data: Option<types::MerchantRecipientData>, } impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { @@ -278,6 +378,16 @@ impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { client_id: client_id.to_owned(), secret: secret.to_owned(), + merchant_data: None, + }), + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Ok(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + merchant_data: Some(merchant_data.clone()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 6f5875247f1..71e2f543c17 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -2,9 +2,10 @@ pub mod api; use std::marker::PhantomData; -use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; -use common_enums::PaymentMethodType; +use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate}; +use common_enums::{CountryAlpha2, PaymentMethodType}; use masking::Secret; + #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { pub flow: PhantomData<F>, @@ -85,6 +86,38 @@ pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentialsResponse, >; +#[derive(Debug, Clone)] +pub struct RecipientCreateRequest { + pub name: String, + pub account_data: RecipientAccountData, + pub address: Option<RecipientCreateAddress>, +} + +#[derive(Debug, Clone)] +pub struct RecipientCreateResponse { + pub recipient_id: String, +} + +#[derive(Debug, Clone)] +pub enum RecipientAccountData { + Iban(Secret<String>), + Bacs { + sort_code: Secret<String>, + account_number: Secret<String>, + }, +} + +#[derive(Debug, Clone)] +pub struct RecipientCreateAddress { + pub street: String, + pub city: String, + pub postal_code: String, + pub country: CountryAlpha2, +} + +pub type RecipientCreateRouterData = + PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; + pub type PaymentAuthLinkTokenType = dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; @@ -97,6 +130,12 @@ pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration BankAccountCredentialsResponse, >; +pub type PaymentInitiationRecipientCreateType = dyn self::api::ConnectorIntegration< + RecipientCreate, + RecipientCreateRequest, + RecipientCreateResponse, +>; + #[derive(Clone, Debug, strum::EnumString, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodAuthConnectors { @@ -129,12 +168,38 @@ impl ErrorResponse { } } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub enum MerchantAccountData { + Iban { + iban: Secret<String>, + name: String, + }, + Bacs { + account_number: Secret<String>, + sort_code: Secret<String>, + name: String, + }, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantRecipientData { + RecipientId(Secret<String>), + WalletId(Secret<String>), + AccountData(MerchantAccountData), +} + #[derive(Default, Debug, Clone, serde::Deserialize)] pub enum ConnectorAuthType { BodyKey { client_id: Secret<String>, secret: Secret<String>, }, + OpenBankingAuth { + api_key: Secret<String>, + key1: Secret<String>, + merchant_data: MerchantRecipientData, + }, #[default] NoKey, } diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs index 3684e34ec05..d4edf160985 100644 --- a/crates/pm_auth/src/types/api.rs +++ b/crates/pm_auth/src/types/api.rs @@ -10,7 +10,10 @@ use masking::Maskable; use crate::{ core::errors::ConnectorError, - types::{self as auth_types, api::auth_service::AuthService}, + types::{ + self as auth_types, + api::auth_service::{AuthService, PaymentInitiation}, + }, }; #[async_trait::async_trait] @@ -125,9 +128,9 @@ where } } -pub trait AuthServiceConnector: AuthService + Send + Debug {} +pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {} -impl<T: Send + Debug + AuthService> AuthServiceConnector for T {} +impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {} pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs index 35d44970d51..498b6bec40e 100644 --- a/crates/pm_auth/src/types/api/auth_service.rs +++ b/crates/pm_auth/src/types/api/auth_service.rs @@ -1,6 +1,7 @@ use crate::types::{ BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, - ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, + ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest, + RecipientCreateResponse, }; pub trait AuthService: @@ -11,6 +12,8 @@ pub trait AuthService: { } +pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {} + #[derive(Debug, Clone)] pub struct LinkToken; @@ -38,3 +41,11 @@ pub trait AuthServiceBankAccountCredentials: > { } + +#[derive(Debug, Clone)] +pub struct RecipientCreate; + +pub trait PaymentInitiationRecipientCreate: + super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse> +{ +} diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index a74f16cee79..f76437ff97f 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -848,8 +848,18 @@ pub(crate) fn into_stripe_next_action( bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { - StripeNextAction::ThirdPartySdkSessionToken { session_token } + match session_token { + Some(payments::SessionTokenType::Wallet(token)) => { + StripeNextAction::ThirdPartySdkSessionToken { + session_token: Some(token), + } + } + _ => StripeNextAction::ThirdPartySdkSessionToken { + session_token: None, + }, + } } + payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index a05a8c241d0..51c83624763 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -421,7 +421,16 @@ pub(crate) fn into_stripe_next_action( bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { - StripeNextAction::ThirdPartySdkSessionToken { session_token } + match session_token { + Some(payments::SessionTokenType::Wallet(token)) => { + StripeNextAction::ThirdPartySdkSessionToken { + session_token: Some(token), + } + } + _ => StripeNextAction::ThirdPartySdkSessionToken { + session_token: None, + }, + } } payments::NextActionData::QrCodeInformation { image_data_url, diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index f89d1811988..b2a67712ce9 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -361,5 +361,6 @@ pub(crate) async fn fetch_raw_secrets( connector_onboarding, cors: conf.cors, unmasked_headers: conf.unmasked_headers, + locker_open_banking_connectors: conf.locker_open_banking_connectors, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index dc4826dfed6..89b5b81b1a4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -116,6 +116,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "olap")] pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, pub unmasked_headers: UnmaskedHeaders, + pub locker_open_banking_connectors: LockerBasedRecipientConnectorList, } #[derive(Debug, Deserialize, Clone, Default)] @@ -511,6 +512,7 @@ pub struct Connectors { pub paypal: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, + pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, @@ -624,6 +626,11 @@ pub struct ApplePayDecryptConifg { pub apple_pay_merchant_cert_key: Secret<String>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct LockerBasedRecipientConnectorList { + pub connector_list: HashSet<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index eccdf3f9ddf..cd829718652 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -37,6 +37,7 @@ pub mod payme; pub mod paypal; pub mod payu; pub mod placetopay; +pub mod plaid; pub mod powertranz; pub mod prophetpay; pub mod rapyd; @@ -67,8 +68,8 @@ pub use self::{ 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, placetopay::Placetopay, - powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, riskified::Riskified, - shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, - threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt, wise::Wise, - worldline::Worldline, worldpay::Worldpay, zen::Zen, + plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, + riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, + stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt, + wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen, }; diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 67e319ddc22..ed1ea772898 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -210,6 +210,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::SamsungPay | PaymentMethodType::Evoucher | PaymentMethodType::Cashapp + | PaymentMethodType::OpenBanking | PaymentMethodType::UpiCollect => { capture_method_not_supported!(connector, capture_method, payment_method_type) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index c44d590e2f1..1bbb336441d 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2339,7 +2339,8 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> Ok(AdyenPaymentMethod::Trustly) } payments::BankRedirectData::Interac { .. } - | payments::BankRedirectData::Przelewy24 { .. } => { + | payments::BankRedirectData::Przelewy24 { .. } + | payments::BankRedirectData::OpenBanking { .. } => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Adyen", diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 8b7ab0da7f2..4f3aa9be9ca 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -385,6 +385,7 @@ impl | api_models::enums::PaymentMethodType::PagoEfectivo | api_models::enums::PaymentMethodType::PermataBankTransfer | api_models::enums::PaymentMethodType::OpenBankingUk + | api_models::enums::PaymentMethodType::OpenBanking | api_models::enums::PaymentMethodType::PayBright | api_models::enums::PaymentMethodType::Paypal | api_models::enums::PaymentMethodType::Pix diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 07488271aea..8ff490d265c 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -608,6 +608,7 @@ fn get_payment_details_and_product( | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } | api_models::payments::BankRedirectData::OpenBankingUk { .. } + | api_models::payments::BankRedirectData::OpenBanking { .. } | api_models::payments::BankRedirectData::Przelewy24 { .. } | api_models::payments::BankRedirectData::Trustly { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 1312eadadf7..baf511cae0b 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -820,6 +820,7 @@ impl<F> | payments::BankRedirectData::Trustly { .. } | payments::BankRedirectData::OnlineBankingFpx { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::OpenBankingUk { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index a584fe98165..46df4a0b21d 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -398,6 +398,7 @@ fn get_payment_source( | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::OpenBanking { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } => { diff --git a/crates/router/src/connector/plaid.rs b/crates/router/src/connector/plaid.rs new file mode 100644 index 00000000000..1d884a22979 --- /dev/null +++ b/crates/router/src/connector/plaid.rs @@ -0,0 +1,789 @@ +pub mod transformers; + +use std::fmt::Debug; + +use common_utils::ext_traits::ByteSliceExt; +use error_stack::ResultExt; +use transformers as plaid; + +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, + headers, + services::{ + self, + request::{self, Mask}, + ConnectorIntegration, ConnectorValidation, + }, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + transformers::ForeignFrom, + ErrorResponse, RequestContent, Response, + }, + utils::BytesExt, +}; + +#[derive(Debug, Clone)] +pub struct Plaid; + +impl api::Payment for Plaid {} +impl api::PaymentSession for Plaid {} +impl api::ConnectorAccessToken for Plaid {} +impl api::MandateSetup for Plaid {} +impl api::PaymentAuthorize for Plaid {} +impl api::PaymentSync for Plaid {} +impl api::PaymentCapture for Plaid {} +impl api::PaymentVoid for Plaid {} +impl api::Refund for Plaid {} +impl api::RefundExecute for Plaid {} +impl api::RefundSync for Plaid {} +impl api::PaymentToken for Plaid {} +impl api::PaymentsPostProcessing for Plaid {} +impl api::ConnectorVerifyWebhookSource for Plaid {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Plaid +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid +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(), + self.get_content_type().to_string().into(), + )]; + let mut auth = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth); + Ok(header) + } +} + +impl ConnectorCommon for Plaid { + fn id(&self) -> &'static str { + "plaid" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.plaid.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = plaid::PlaidAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let client_id = auth.client_id.into_masked(); + let secret = auth.secret.into_masked(); + + Ok(vec![ + ("PLAID-CLIENT-ID".to_string(), client_id), + ("PLAID-SECRET".to_string(), secret), + ]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: plaid::PlaidErrorResponse = + res.response + .parse_struct("PlaidErrorResponse") + .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: crate::consts::NO_ERROR_CODE.to_string(), + message: response.error_message, + reason: response.display_message, + attempt_status: None, + connector_transaction_id: None, + }) + } +} + +impl ConnectorValidation for Plaid { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Plaid +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Plaid +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Plaid +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Plaid +{ + 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> { + Ok(format!( + "{}/payment_initiation/payment/create", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = + plaid::PlaidRouterData::try_from((Some(req.request.amount as f64), req))?; + let connector_req = plaid::PlaidPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_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, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: plaid::PlaidPaymentsResponse = res + .response + .parse_struct("PlaidPaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Plaid +{ + 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_request_body( + &self, + req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = plaid::PlaidRouterData::try_from((None, req))?; + let connector_req = plaid::PlaidSyncRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + 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!( + "{}/payment_initiation/payment/get", + self.base_url(connectors) + )) + } + + 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)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: plaid::PlaidSyncResponse = res + .response + .parse_struct("PlaidSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for Plaid +{ + fn get_headers( + &self, + req: &types::PaymentsPostProcessingRouterData, + 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::PaymentsPostProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/link/token/create", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsPostProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = plaid::PlaidRouterData::try_from((None, req))?; + let connector_req = plaid::PlaidLinkTokenRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PaymentsPostProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPostProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPostProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPostProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPostProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> { + let response: plaid::PlaidLinkTokenResponse = res + .response + .parse_struct("PlaidLinkTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Plaid +{ + 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, + _connectors: &settings::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> { + 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, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: plaid::PlaidPaymentsResponse = res + .response + .parse_struct("Plaid PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Plaid +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Plaid { + 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>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = + plaid::PlaidRouterData::try_from((Some(req.request.refund_amount as f64), req))?; + let connector_req = plaid::PlaidRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(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)?) + .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: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: plaid::RefundResponse = res + .response + .parse_struct("plaid RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Plaid { + 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)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: plaid::RefundResponse = res + .response + .parse_struct("plaid RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + api::VerifyWebhookSource, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + > for Plaid +{ + fn get_headers( + &self, + req: &types::RouterData< + api::VerifyWebhookSource, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + >, + 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::RouterData< + api::VerifyWebhookSource, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + >, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/webhook_verification_key/get", + self.base_url(connectors) + )) + } + + fn build_request( + &self, + req: &types::VerifyWebhookSourceRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::VerifyWebhookSourceType::get_url( + self, req, connectors, + )?) + .headers(types::VerifyWebhookSourceType::get_headers( + self, req, connectors, + )?) + .set_body(types::VerifyWebhookSourceType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn get_request_body( + &self, + req: &types::RouterData< + api::VerifyWebhookSource, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + >, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = plaid::PlaidWebhookVerificationRequest::try_from(&req.request)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn handle_response( + &self, + data: &types::VerifyWebhookSourceRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ConnectorError> { + let response: plaid::PlaidWebhookVerificationResponse = res + .response + .parse_struct("PlaidWebhookVerificationResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + plaid::process_plaid_jwt_header(&data.request, &response)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Plaid { + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + let payload: plaid::PlaidPaymentsWebhookBody = request + .body + .parse_struct("PlaidPaymentsWebhookBody") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + Ok(api::ObjectReferenceId::PaymentId( + api::PaymentIdType::ConnectorTransactionId(payload.payment_id), + )) + } + + fn get_webhook_event_type( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + let payload: plaid::PlaidPaymentsWebhookBody = request + .body + .parse_struct("PlaidPaymentsWebhookBody") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + Ok(api::IncomingWebhookEvent::foreign_from( + payload.new_payment_status, + )) + } + + fn get_webhook_resource_object( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + let payload: plaid::PlaidPaymentsWebhookBody = request + .body + .parse_struct("PlaidPaymentsWebhookBody") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + + Ok(Box::new(payload)) + } +} diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs new file mode 100644 index 00000000000..81c0c7dde05 --- /dev/null +++ b/crates/router/src/connector/plaid/transformers.rs @@ -0,0 +1,678 @@ +use actix_http::header::HeaderMap; +use common_enums::Currency; +use error_stack::{IntoReport, ResultExt}; +use jsonwebtoken; +use masking::{PeekInterface, Secret}; +use ring::digest; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + types::{self, api, storage::enums, transformers::ForeignFrom}, + utils::ext_traits::OptionExt, +}; + +const PLAID_VERIFICATION_HEADER: &str = "Plaid-Verification"; + +//TODO: Fill the struct with respective fields +pub struct PlaidRouterData<T> { + pub amount: Option<f64>, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> TryFrom<(Option<f64>, T)> for PlaidRouterData<T> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from((amount, item): (Option<f64>, 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, + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct PlaidPaymentsRequest { + amount: PlaidAmount, + recipient_id: String, + reference: String, + #[serde(skip_serializing_if = "Option::is_none")] + schedule: Option<PlaidSchedule>, + #[serde(skip_serializing_if = "Option::is_none")] + options: Option<PlaidOptions>, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidAmount { + currency: Currency, + value: f64, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidSchedule { + interval: String, + interval_execution_day: String, + start_date: String, + end_date: Option<String>, + adjusted_start_date: Option<String>, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidOptions { + request_refund_details: bool, + iban: Option<String>, + bacs: Option<PlaidBacs>, + scheme: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidBacs { + acount: Secret<String>, + sort_code: Secret<String>, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct PlaidLinkTokenRequest { + client_name: String, + country_codes: Vec<String>, + language: String, + products: Vec<String>, + user: User, + payment_initiation: PlaidPaymentInitiation, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct User { + pub client_user_id: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidPaymentInitiation { + payment_id: String, +} + +impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PlaidRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + api::PaymentMethodData::BankRedirect(ref bank) => match bank { + api_models::payments::BankRedirectData::OpenBanking { .. } => { + let amount = + item.amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?; + let currency = item.router_data.request.currency; + let reference = "Some ref".to_string(); + let recipient_val = item + .router_data + .connector_meta_data + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_customer", + })? + .peek() + .clone(); + + let recipient_type = + serde_json::from_value::<types::MerchantRecipientData>(recipient_val) + .into_report() + .change_context(errors::ConnectorError::ParsingFailed)?; + let recipient_id = match recipient_type { + types::MerchantRecipientData::RecipientId(id) => Ok(id.peek().to_string()), + _ => Err(errors::ConnectorError::NotSupported { + message: "recipient_id not found, other methods".to_string(), + connector: "plaid", + }), + } + .into_report()?; + + Ok(Self { + amount: PlaidAmount { + currency, + value: amount, + }, + reference, + recipient_id, + schedule: None, + options: None, + }) + } + _ => Err( + errors::ConnectorError::NotImplemented("Payment method type".to_string()) + .into(), + ), + }, + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +impl TryFrom<&PlaidRouterData<&types::PaymentsSyncRouterData>> for PlaidSyncRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PlaidRouterData<&types::PaymentsSyncRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.connector_transaction_id { + types::ResponseId::ConnectorTransactionId(ref id) => Ok(Self { + payment_id: id.clone(), + }), + _ => Err( + errors::ConnectorError::NotImplemented("ResponseId for Plaid".to_string()).into(), + ), + } + } +} + +impl TryFrom<&PlaidRouterData<&types::PaymentsPostProcessingRouterData>> for PlaidLinkTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PlaidRouterData<&types::PaymentsPostProcessingRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + api::PaymentMethodData::BankRedirect(ref bank) => match bank { + api_models::payments::BankRedirectData::OpenBanking { .. } => Ok(Self { + // discuss this with folks + client_name: "Hyperswitch".to_string(), + country_codes: vec!["GB".to_string()], + language: "en".to_string(), + products: vec!["payment_initiation".to_string()], + user: User { + client_user_id: item + .router_data + .request + .customer_id + .clone() + .unwrap_or("default cust".to_string()), + }, + payment_initiation: PlaidPaymentInitiation { + payment_id: item + .router_data + .request + .connector_transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_transaction_id", + })?, + }, + }), + _ => Err( + errors::ConnectorError::NotImplemented("Payment method type".to_string()) + .into(), + ), + }, + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PlaidAuthType { + pub client_id: Secret<String>, + pub secret: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + .. + } => Ok(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[derive(strum::Display)] +pub enum PlaidPaymentStatus { + PaymentStatusInputNeeded, + PaymentStatusInitiated, + PaymentStatusInsuficientFunds, + PaymentStatusFailed, + PaymentStatusBlcoked, + PaymentStatusCancelled, + PaymentStatusExecuted, + PaymentStatusSettled, + PaymentStatusEstablished, + PaymentStatusRejected, + #[default] + PaymentStatusAuthorising, +} + +impl From<PlaidPaymentStatus> for enums::AttemptStatus { + fn from(item: PlaidPaymentStatus) -> Self { + match item { + // Double check these with someone + PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing, + PlaidPaymentStatus::PaymentStatusBlcoked => Self::AuthorizationFailed, + PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided, + PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized, + PlaidPaymentStatus::PaymentStatusExecuted => Self::Authorized, + PlaidPaymentStatus::PaymentStatusFailed => Self::Failure, + PlaidPaymentStatus::PaymentStatusInitiated => Self::AuthenticationPending, + PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending, + PlaidPaymentStatus::PaymentStatusInsuficientFunds => Self::AuthorizationFailed, + PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed, + PlaidPaymentStatus::PaymentStatusSettled => Self::Charged, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PlaidPaymentsResponse { + status: PlaidPaymentStatus, + payment_id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PlaidPaymentsResponse, 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.payment_id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.payment_id), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidLinkTokenResponse { + link_token: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let session_token = Some(api::OpenBankingSessionToken { + open_banking_session_token: item.response.link_token, + }); + + Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::PostProcessingResponse { session_token }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidSyncRequest { + payment_id: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidSyncResponse { + payment_id: String, + amount: PlaidAmount, + status: PlaidPaymentStatus, + recipient_id: String, + reference: String, + last_status_update: String, + adjusted_reference: Option<String>, + schedule: Option<PlaidSchedule>, + iban: Option<String>, + bacs: Option<PlaidBacs>, + scheme: Option<String>, + adjusted_scheme: Option<String>, + request_id: String, + // TODO: add refund related objects +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let status = enums::AttemptStatus::from(item.response.status.clone()); + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(types::ErrorResponse { + code: item.response.status.clone().to_string(), + message: item.response.status.clone().to_string(), + reason: Some(item.response.status.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(item.response.payment_id), + }) + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.payment_id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.payment_id), + incremental_authorization_allowed: None, + }) + }, + ..item.data + }) + } +} + +// TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct PlaidRefundRequest { + pub amount: f64, +} + +impl<F> TryFrom<&PlaidRouterData<&types::RefundsRouterData<F>>> for PlaidRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PlaidRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "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 + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidPaymentsWebhookBody { + pub webhook_type: String, + pub webhook_code: String, + pub payment_id: String, + pub new_payment_status: PlaidPaymentStatus, + pub old_payment_status: PlaidPaymentStatus, + pub original_reference: String, + pub adjusted_reference: String, + pub original_start_date: String, + pub adjusted_start_date: String, + pub timestamp: String, + pub environment: String, +} + +impl ForeignFrom<PlaidPaymentStatus> for api::IncomingWebhookEvent { + fn foreign_from(status: PlaidPaymentStatus) -> Self { + match status { + // Double check these with someone + PlaidPaymentStatus::PaymentStatusAuthorising => Self::PaymentIntentProcessing, + PlaidPaymentStatus::PaymentStatusBlcoked => Self::PaymentIntentAuthorizationFailure, + PlaidPaymentStatus::PaymentStatusCancelled => Self::PaymentIntentCancelled, + PlaidPaymentStatus::PaymentStatusEstablished => Self::PaymentIntentAuthorizationSuccess, + PlaidPaymentStatus::PaymentStatusExecuted => Self::PaymentIntentSuccess, + PlaidPaymentStatus::PaymentStatusFailed => Self::PaymentIntentFailure, + PlaidPaymentStatus::PaymentStatusInitiated => Self::PaymentIntentAuthorizationSuccess, + PlaidPaymentStatus::PaymentStatusInputNeeded => Self::PaymentActionRequired, + PlaidPaymentStatus::PaymentStatusInsuficientFunds => Self::PaymentIntentFailure, + PlaidPaymentStatus::PaymentStatusRejected => Self::PaymentIntentFailure, + PlaidPaymentStatus::PaymentStatusSettled => Self::PaymentIntentSuccess, + } + } +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidWebhookVerificationRequest { + pub key_id: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidJWK { + kid: String, + alg: String, + created_at: i64, + expired_at: Option<i64>, + pub x: String, + pub y: String, + #[serde(rename = "use")] + _use: String, + kty: String, + crv: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct PlaidWebhookVerificationResponse { + key: PlaidJWK, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +struct PlaidJWTPayload { + iat: i64, + request_body_sha256: String, +} + +impl TryFrom<&types::VerifyWebhookSourceRequestData> for PlaidWebhookVerificationRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(req: &types::VerifyWebhookSourceRequestData) -> Result<Self, Self::Error> { + let kid = get_data_from_verification_header(&req.webhook_headers)?; + + Ok(Self { key_id: kid }) + } +} + +impl + TryFrom< + types::ResponseRouterData< + api::VerifyWebhookSource, + PlaidWebhookVerificationResponse, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + >, + > for types::VerifyWebhookSourceRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + api::VerifyWebhookSource, + PlaidWebhookVerificationResponse, + types::VerifyWebhookSourceRequestData, + types::VerifyWebhookSourceResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::VerifyWebhookSourceResponseData { + verify_webhook_status: types::VerifyWebhookStatus::SourceVerified, + }), + ..item.data + }) + } +} +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidErrorResponse { + pub display_message: Option<String>, + pub error_code: Option<String>, + pub error_message: String, + pub error_type: Option<String>, +} + +fn is_payment_failure(status: enums::AttemptStatus) -> bool { + match status { + common_enums::AttemptStatus::AuthenticationFailed + | common_enums::AttemptStatus::AuthorizationFailed + | common_enums::AttemptStatus::CaptureFailed + | common_enums::AttemptStatus::VoidFailed + | common_enums::AttemptStatus::Failure => true, + common_enums::AttemptStatus::Started + | common_enums::AttemptStatus::RouterDeclined + | common_enums::AttemptStatus::AuthenticationPending + | common_enums::AttemptStatus::AuthenticationSuccessful + | common_enums::AttemptStatus::Authorized + | common_enums::AttemptStatus::Charged + | common_enums::AttemptStatus::Authorizing + | common_enums::AttemptStatus::CodInitiated + | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidInitiated + | common_enums::AttemptStatus::CaptureInitiated + | common_enums::AttemptStatus::AutoRefunded + | common_enums::AttemptStatus::PartialCharged + | common_enums::AttemptStatus::PartialChargedAndChargeable + | common_enums::AttemptStatus::Unresolved + | common_enums::AttemptStatus::Pending + | common_enums::AttemptStatus::PaymentMethodAwaited + | common_enums::AttemptStatus::ConfirmationAwaited + | common_enums::AttemptStatus::DeviceDataCollectionPending => false, + } +} + +fn get_data_from_verification_header( + headers: &HeaderMap, +) -> Result<String, error_stack::Report<errors::ConnectorError>> { + let plaid_header = headers + .get(PLAID_VERIFICATION_HEADER) + .get_required_value(PLAID_VERIFICATION_HEADER) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)? + .to_str() + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to convert JWT token to string")?; + + let jwt_header = jsonwebtoken::decode_header(plaid_header) + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to get JWT Header for Plaid")?; + + jwt_header + .kid + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) + .into_report() + .attach_printable("Failed to get kid from JWT Header for Plaid") +} + +pub fn process_plaid_jwt_header( + req: &types::VerifyWebhookSourceRequestData, + res: &PlaidWebhookVerificationResponse, +) -> Result<(), error_stack::Report<errors::ConnectorError>> { + let plaid_header = req + .webhook_headers + .get(PLAID_VERIFICATION_HEADER) + .get_required_value(PLAID_VERIFICATION_HEADER) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)? + .to_str() + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to convert JWT token to string")?; + + let key = jsonwebtoken::DecodingKey::from_ec_components(&res.key.x, &res.key.y) + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to from Decoding key for JWT token")?; + + let decoded = jsonwebtoken::decode::<PlaidJWTPayload>( + plaid_header, + &key, + &jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::ES256), + ) + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to validate JWT token")?; + + let body_value = hex::decode(decoded.claims.request_body_sha256) + .into_report() + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to hex-decode plaid webhook request_body_sha256")?; + + let payload_digest = digest::digest(&digest::SHA256, req.webhook_body.as_slice()); + + if payload_digest.as_ref() != body_value.as_slice() { + return Err(errors::ConnectorError::WebhookSourceVerificationFailed.into()); + } + + Ok(()) +} diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 97c19c49af8..7d4ee582485 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -411,6 +411,7 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { | payments::BankRedirectData::OnlineBankingPoland { .. } | payments::BankRedirectData::OnlineBankingSlovakia { .. } | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::OnlineBankingFpx { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } => { Err(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 1e5501575ad..dfa5c509cc3 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -305,15 +305,7 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { api_key: api_key.to_owned(), key1: key1.to_owned(), }), - - types::ConnectorAuthType::HeaderKey { .. } - | types::ConnectorAuthType::SignatureKey { .. } - | types::ConnectorAuthType::MultiAuthKey { .. } - | types::ConnectorAuthType::CurrencyAuthKey { .. } - | types::ConnectorAuthType::TemporaryAuth { .. } - | types::ConnectorAuthType::NoKey { .. } => { - Err(errors::ConnectorError::FailedToObtainAuthType.into()) - } + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index d08f28d1a84..d5a1a58ec0f 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -654,6 +654,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingUk + | enums::PaymentMethodType::OpenBanking | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pse @@ -952,6 +953,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodType { | payments::BankRedirectData::OnlineBankingSlovakia { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::Trustly { .. } => { Err(errors::ConnectorError::NotSupported { message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), @@ -1183,6 +1185,7 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre | payments::BankRedirectData::Trustly { .. } | payments::BankRedirectData::OnlineBankingFpx { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::OpenBankingUk { .. } => Ok(Self::default()), } } @@ -1680,6 +1683,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData { | payments::BankRedirectData::OnlineBankingSlovakia { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::Trustly { .. } => { Err(errors::ConnectorError::NotSupported { message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 79850decb69..1fa9a4aebe3 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -17,6 +17,7 @@ use crate::{ }, consts, core::errors, + headers::NONCE, services, types::{self, api, storage::enums, BrowserInformation}, }; @@ -246,6 +247,7 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } | api_models::payments::BankRedirectData::OpenBankingUk { .. } + | api_models::payments::BankRedirectData::OpenBanking { .. } | api_models::payments::BankRedirectData::Przelewy24 { .. } | api_models::payments::BankRedirectData::Trustly { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index b7c9a6826ce..c1eb52a1a19 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -133,6 +133,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::BankRedirectData::Sofort { .. } | api_models::payments::BankRedirectData::Trustly { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } + | api_models::payments::BankRedirectData::OpenBanking { .. } | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Volt"), diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 1eb22fc52d2..caca9a41770 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -417,6 +417,7 @@ fn make_bank_redirect_request( | payments::BankRedirectData::OnlineBankingPoland { .. } | payments::BankRedirectData::OnlineBankingSlovakia { .. } | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::OpenBanking { .. } | payments::BankRedirectData::Przelewy24 { .. } | payments::BankRedirectData::Sofort { .. } | payments::BankRedirectData::Trustly { .. } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index ebea61304a1..5497969ccc1 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -737,6 +737,7 @@ impl TryFrom<&api_models::payments::BankRedirectData> for ZenPaymentsRequest { | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } | api_models::payments::BankRedirectData::OpenBankingUk { .. } + | api_models::payments::BankRedirectData::OpenBanking { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { Err(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 0eaabf8652c..87397879dde 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -10,24 +10,28 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; -use diesel_models::configs; +use diesel_models::{configs, encryption}; use error_stack::{report, FutureExt, IntoReport, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; -use pm_auth::connector::plaid::transformers::PlaidAuthType; +use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; +use regex::Regex; +use serde_json; use uuid::Uuid; use crate::{ consts, core::{ errors::{self, RouterResponse, RouterResult, StorageErrorExt}, + payment_methods::{cards, transformers}, payments::helpers, + pm_auth::helpers::PaymentAuthConnectorDataExt, routing::helpers as routing_helpers, utils as core_utils, }, db::StorageInterface, routes::{metrics, AppState}, - services::{self, api as service_api}, + services::{self, api as service_api, pm_auth as payment_initiation_service}, types::{ self, api, domain::{ @@ -786,7 +790,9 @@ pub async fn create_payment_connector( api_enums::convert_authentication_connector(req.connector_name.to_string().as_str()); if pm_auth_connector.is_some() { - if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth + && req.connector_type != api_enums::ConnectorType::PaymentProcessor + { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), }) @@ -852,6 +858,16 @@ pub async fn create_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; + let auth = process_open_banking_connectors( + &state, + merchant_id.as_str(), + &key_store, + auth, + &req.connector_type, + &req.connector_name, + ) + .await?; + validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata).map_err(|err| { match *err.current_context() { errors::ConnectorError::InvalidConnectorName => { @@ -892,7 +908,7 @@ pub async fn create_payment_connector( let (connector_status, disabled) = validate_status_and_disabled( req.status, req.disabled, - auth, + auth.clone(), // The validate_status_and_disabled function will use this value only // when the status can be active. So we are passing this as fallback. api_enums::ConnectorStatus::Active, @@ -912,17 +928,19 @@ pub async fn create_payment_connector( } } + let connector_auth = serde_json::to_value(auth) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encoding to serde_json::Value, ConnectorAuthType")?; + let conn_auth = Secret::new(connector_auth); + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, connector_name: req.connector_name.to_string(), merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"), connector_account_details: domain_types::encrypt( - req.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?, + conn_auth, key_store.key.peek(), ) .await @@ -1987,3 +2005,288 @@ pub fn validate_status_and_disabled( Ok((connector_status, disabled)) } + +async fn process_open_banking_connectors( + state: &AppState, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + auth: types::ConnectorAuthType, + connector_type: &api_enums::ConnectorType, + connector: &api_enums::Connector, +) -> RouterResult<types::ConnectorAuthType> { + match &auth { + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => { + // incorporate a connector check as well + if connector_type != &api_enums::ConnectorType::PaymentProcessor { + return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "OpenBankingAuth type needs to be coupled with a payment connector" + .to_string(), + } + .into()); + } + + let new_auth = match merchant_data { + types::MerchantRecipientData::AccountData(acc_data) => { + validate_bank_account_data(acc_data)?; + + let connector_name = api_enums::Connector::to_string(connector); + + let locker_based_connector_list = + state.conf.locker_open_banking_connectors.clone(); + let contains = locker_based_connector_list + .connector_list + .get(connector_name.as_str()); + + let recipient_id = if let Some(_conn) = contains { + locker_recipient_create_call(state, merchant_id, key_store, acc_data).await + } else { + connector_recipient_create_call( + state, + merchant_id, + connector_name, + &auth, + acc_data, + ) + .await + } + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to get recipient_id")?; + + // data.merchant_data = api_models::admin::MerchantRecipientData::RecipientID( + // Secret::new(recipient_id), + // ); + + types::ConnectorAuthType::OpenBankingAuth { + api_key: api_key.clone(), + key1: key1.clone(), + merchant_data: types::MerchantRecipientData::RecipientId(Secret::new( + recipient_id, + )), + } + } + _ => auth.clone(), + }; + + Ok(new_auth) + } + _ => Ok(auth.clone()), + } +} + +fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> { + match data { + types::MerchantAccountData::Iban { iban, .. } => { + if iban.peek().len() > 34 { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "IBAN length must be up to 34 characters".to_string(), + } + .into()); + } + let pattern = Regex::new(r"^[A-Z0-9]*$") + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to create regex pattern")?; + + let mut iban = iban.peek().to_string(); + + if !pattern.is_match(iban.as_str()) { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "IBAN data must be alphanumeric".to_string(), + } + .into()); + } + + // MOD check + let first_4 = iban.chars().take(4).collect::<String>(); + iban.push_str(first_4.as_str()); + let len = iban.len(); + + let rearranged_iban = iban + .chars() + .rev() + .take(len - 4) + .collect::<String>() + .chars() + .rev() + .collect::<String>(); + + let mut result = String::new(); + + for c in rearranged_iban.chars() { + match c { + 'A'..='Z' => { + let digit = (c as u8 - b'A') + 10; + result.push_str(&format!("{:02}", digit)); + } + _ => result.push(c), + } + } + + let num = result + .parse::<u128>() + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to validate IBAN")?; + + if num % 97 != 1 { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid IBAN".to_string(), + } + .into()); + } + + Ok(()) + } + types::MerchantAccountData::Bacs { + account_number, + sort_code, + .. + } => { + if account_number.peek().len() > 8 || sort_code.peek().len() != 6 { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid BACS numbers".to_string(), + } + .into()); + } + + Ok(()) + } + } +} + +async fn connector_recipient_create_call( + state: &AppState, + merchant_id: &str, + connector_name: String, + auth: &types::ConnectorAuthType, + data: &types::MerchantAccountData, +) -> RouterResult<String> { + let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( + connector_name.as_str(), + )?; + + let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone()) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while converting ConnectorAuthType")?; + + let connector_integration: pm_auth_types::api::BoxedConnectorIntegration< + '_, + pm_auth_types::api::auth_service::RecipientCreate, + pm_auth_types::RecipientCreateRequest, + pm_auth_types::RecipientCreateResponse, + > = connector.connector.get_connector_integration(); + + let req = match data { + types::MerchantAccountData::Iban { iban, name } => pm_auth_types::RecipientCreateRequest { + name: name.clone(), + account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()), + address: None, + }, + types::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + } => pm_auth_types::RecipientCreateRequest { + name: name.clone(), + account_data: pm_auth_types::RecipientAccountData::Bacs { + sort_code: sort_code.clone(), + account_number: account_number.clone(), + }, + address: None, + }, + }; + + let router_data = pm_auth_types::RecipientCreateRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_id.to_owned()), + connector: Some(connector_name), + request: req, + response: Ok(pm_auth_types::RecipientCreateResponse { + recipient_id: "".to_string(), + }), + connector_http_status_code: None, + connector_auth_type: auth, + }; + + let resp = payment_initiation_service::execute_connector_processing_step( + state, + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling recipient create connector api")?; + + let recipient_create_resp = + resp.response + .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let recipient_id = recipient_create_resp.recipient_id; + + Ok(recipient_id) +} + +async fn locker_recipient_create_call( + state: &AppState, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + data: &types::MerchantAccountData, +) -> RouterResult<String> { + let key = key_store.key.get_inner().peek(); + + let enc_data = async { + serde_json::to_value(data.to_owned()) + .map_err(|err| { + crate::logger::error!("Error while encoding merchant bank account data: {}", err); + errors::VaultError::SavePaymentMethodFailed + }) + .into_report() + .change_context(errors::VaultError::SavePaymentMethodFailed) + .attach_printable("Unable to encode merchant bank account data") + .ok() + .map(|v| { + let secret: Secret<String> = Secret::new(v.to_string()); + secret + }) + .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .await + } + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt merchant bank account data")? + .map(encryption::Encryption::from) + .map(|e| e.into_inner()) + .map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| { + Ok(hex::encode(e.peek())) + })?; + + let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq { + merchant_id, + merchant_customer_id: merchant_id.to_string(), + enc_data, + }); + + let store_resp = cards::call_to_locker_hs( + state, + &payload, + merchant_id, + api_enums::LockerChoice::HyperswitchCardVault, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt merchant bank account data")?; + + Ok(store_resp.card_reference) +} diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 0e3f67c051b..bdf34f095e7 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -90,6 +90,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .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 8b3eed45f9e..3b904e3dd1a 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -17,7 +17,7 @@ use crate::{ domain, fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData}, storage::enums as storage_enums, - BrowserInformation, ConnectorAuthType, ResponseId, RouterData, + BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, AppState, }; @@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; 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 2de6aaab7c7..a947c81ca17 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -17,7 +17,7 @@ use crate::{ FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, utils, AppState, }; @@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; 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 dfe70570047..b9a7cb87e98 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -14,7 +14,7 @@ use crate::{ domain, fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData}, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, AppState, }; @@ -31,6 +31,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; 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 a84d9a771b4..f9aed084663 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -16,7 +16,7 @@ use crate::{ FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, AppState, }; @@ -37,6 +37,7 @@ impl _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 52240bbf39b..f8aa2608261 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -14,13 +14,17 @@ pub mod types; use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter}; use api_models::{self, enums, payments::HeaderPayload}; -use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; +use common_utils::{ + ext_traits::{AsyncExt, StringExt}, + pii, + types::Surcharge, +}; use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; use helpers::ApplePayData; -use masking::Secret; +use masking::{PeekInterface, Secret}; use redis_interface::errors::RedisError; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] @@ -51,7 +55,7 @@ use crate::{ core::{ authentication as authentication_core, errors::{self, CustomResult, RouterResponse, RouterResult}, - payment_methods::PaymentMethodRetrieve, + payment_methods::{self, PaymentMethodRetrieve}, utils, }, db::StorageInterface, @@ -176,6 +180,10 @@ where ) .await?; + let op_ref = &operation; + let should_trigger_post_processing_flows = + matches!(format!("{op_ref:?}").as_str(), "PaymentConfirm"); + let mut connector_http_status_code = None; let mut external_latency = None; if let Some(connector_details) = connector { @@ -243,11 +251,11 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, &merchant_account, &key_store, - connector, + connector.clone(), &operation, &mut payment_data, &customer, @@ -267,7 +275,7 @@ where external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); - operation + payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -276,7 +284,23 @@ where router_data, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } api::ConnectorCallType::Retryable(connectors) => { @@ -298,7 +322,7 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, &merchant_account, &key_store, @@ -333,7 +357,7 @@ where state, &mut payment_data, connectors, - connector_data, + connector_data.clone(), router_data, &merchant_account, &key_store, @@ -355,7 +379,7 @@ where external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); - operation + payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -364,7 +388,23 @@ where router_data, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector_data, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } api::ConnectorCallType::SessionMultiple(connectors) => { @@ -669,7 +709,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>( ) -> RouterResponse<Res> where F: Send + Clone + Sync, - FData: Send + Sync, + FData: Send + Sync + Clone, Op: Operation<F, Req, Ctx> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, Res: transformers::ToResponse<Req, PaymentData<F>, Op>, @@ -1026,7 +1066,10 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>( schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, -) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +) -> RouterResult<( + router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> where F: Send + Clone + Sync, RouterDReq: Send + Sync, @@ -1089,6 +1132,15 @@ where ) .await?; + let merchant_recipient_data = get_merchant_bank_data_for_open_banking_connectors( + &merchant_connector_account, + key_store, + &connector, + state, + merchant_account, + ) + .await?; + let mut router_data = payment_data .construct_router_data( state, @@ -1097,6 +1149,7 @@ where key_store, customer, &merchant_connector_account, + merchant_recipient_data, ) .await?; @@ -1165,7 +1218,9 @@ where .. }) = router_data.response.to_owned() { - payment_data.sessions_token.push(session_token); + payment_data + .sessions_token + .push(api::SessionTokenType::Wallet(session_token)); }; // In case of authorize flow, pre-task and post-tasks are being called in build request @@ -1210,7 +1265,7 @@ where ) .await?; - let router_data_res = if should_continue_further { + let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, @@ -1229,13 +1284,63 @@ where .await } else { Ok(router_data) - }; + }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); - router_data_res + Ok((router_data, merchant_connector_account)) +} + +async fn get_merchant_bank_data_for_open_banking_connectors( + merchant_connector_account: &helpers::MerchantConnectorAccountType, + key_store: &domain::MerchantKeyStore, + connector: &api::ConnectorData, + state: &AppState, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<Option<router_types::MerchantRecipientData>> { + let auth_type: router_types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while parsing value for ConnectorAuthType")?; + let connector_name = enums::Connector::to_string(&connector.connector_name); + let locker_based_connector_list = state.conf.locker_open_banking_connectors.clone(); + let contains = locker_based_connector_list + .connector_list + .get(connector_name.as_str()); + let recipient_id = helpers::get_recipient_id_from_open_banking_auth(&auth_type)?; + let final_recipient_data = if let Some(id) = recipient_id { + if let Some(_con) = contains { + let resp = payment_methods::cards::get_payment_method_from_hs_locker( + state, + key_store, + merchant_account.merchant_id.as_str(), + merchant_account.merchant_id.as_str(), + id.as_str(), + Some(enums::LockerChoice::HyperswitchCardVault), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Merchant bank account data could not be fetched from locker")?; + + let parsed: router_types::MerchantAccountData = resp + .peek() + .to_string() + .parse_struct("MerchantAccountData") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Some(router_types::MerchantRecipientData::AccountData(parsed)) + } else { + Some(router_types::MerchantRecipientData::RecipientId( + Secret::new(id), + )) + } + } else { + None + }; + Ok(final_recipient_data) } async fn blocklist_guard<F, ApiRequest, Ctx>( @@ -1342,6 +1447,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .await?; @@ -1375,7 +1481,9 @@ where session_token, api_models::payments::SessionToken::NoSessionTokenReceived, ) { - payment_data.sessions_token.push(session_token); + payment_data + .sessions_token + .push(api::SessionTokenType::Wallet(session_token)); } } } @@ -1472,6 +1580,7 @@ where key_store, customer, merchant_connector_account, + None, ) .await?; @@ -1603,6 +1712,17 @@ where (router_data, should_continue_payment) } } + Some(api_models::payments::PaymentMethodData::BankRedirect(data)) => match data { + api_models::payments::BankRedirectData::OpenBanking { .. } => { + if connector.connector_name == router_types::Connector::Plaid { + router_data = router_data.preprocessing_steps(state, connector).await?; + (router_data, true) + } else { + (router_data, should_continue_payment) + } + } + _ => (router_data, should_continue_payment), + }, _ => { // 3DS validation for paypal cards after verification (authorize call) if connector.connector_name == router_types::Connector::Paypal @@ -1623,6 +1743,71 @@ where Ok(router_data_and_should_continue_payment) } +#[allow(clippy::too_many_arguments)] +async fn complete_postprocessing_steps_if_required<F, Q, Ctx, RouterDReq>( + state: &AppState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + customer: &Option<domain::Customer>, + merchant_conn_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + payment_data: &mut PaymentData<F>, + _operation: &BoxedOperation<'_, F, Q, Ctx>, +) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +where + F: Send + Clone + Sync, + RouterDReq: Send + Sync, + + router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, + PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, +{ + let mut router_data = payment_data + .construct_router_data( + state, + connector.connector.id(), + merchant_account, + key_store, + customer, + merchant_conn_account, + None, + ) + .await?; + + match payment_data.payment_method_data.clone() { + Some(api_models::payments::PaymentMethodData::BankRedirect(data)) => match data { + api_models::payments::BankRedirectData::OpenBanking { .. } => { + if connector.connector_name == router_types::Connector::Plaid { + router_data = router_data.postprocessing_steps(state, connector).await?; + let token = if let Ok(ref res) = router_data.response { + match res { + router_types::PaymentsResponseData::PostProcessingResponse { + session_token, + } => session_token + .as_ref() + .map(|token| api::SessionTokenType::OpenBanking(token.clone())), + _ => None, + } + } else { + None + }; + if let Some(t) = token { + payment_data.sessions_token.push(t); + } + + Ok(router_data) + } else { + Ok(router_data) + } + } + _ => Ok(router_data), + }, + _ => Ok(router_data), + } +} + pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } @@ -2062,7 +2247,7 @@ where pub refunds: Vec<storage::Refund>, pub disputes: Vec<storage::Dispute>, pub attempts: Option<Vec<storage::PaymentAttempt>>, - pub sessions_token: Vec<api::SessionToken>, + pub sessions_token: Vec<api::SessionTokenType>, pub card_cvc: Option<Secret<String>>, pub email: Option<pii::Email>, pub creds_identifier: Option<String>, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index fe4a504861d..bdca658a89f 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -25,6 +25,7 @@ use crate::{ }; #[async_trait] +#[allow(clippy::too_many_arguments)] pub trait ConstructFlowSpecificData<F, Req, Res> { async fn construct_router_data<'a>( &self, @@ -34,6 +35,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, Req, Res>>; } @@ -93,6 +95,19 @@ pub trait Feature<F, T> { Ok(self) } + async fn postprocessing_steps<'a>( + self, + _state: &AppState, + _connector: &api::ConnectorData, + ) -> RouterResult<Self> + where + F: Clone, + Self: Sized, + dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, + { + Ok(self) + } + async fn create_connector_customer<'a>( &self, _state: &AppState, @@ -146,6 +161,7 @@ impl<const T: u8> default_imp_for_complete_authorize!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Bitpay, @@ -295,6 +311,7 @@ impl<const T: u8> default_imp_for_create_customer!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -378,6 +395,7 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec default_imp_for_connector_redirect_response!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Bitpay, @@ -430,6 +448,7 @@ impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> { default_imp_for_connector_request_id!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -515,6 +534,7 @@ impl<const T: u8> default_imp_for_accept_dispute!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -620,6 +640,7 @@ impl<const T: u8> default_imp_for_file_upload!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -702,6 +723,7 @@ impl<const T: u8> default_imp_for_submit_evidence!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -784,6 +806,7 @@ impl<const T: u8> default_imp_for_defend_dispute!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -853,6 +876,21 @@ macro_rules! default_imp_for_pre_processing_steps{ }; } +macro_rules! default_imp_for_post_processing_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl api::PaymentsPostProcessing for $path::$connector {} + impl + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -867,6 +905,7 @@ impl<const T: u8> default_imp_for_pre_processing_steps!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -913,6 +952,75 @@ default_imp_for_pre_processing_steps!( connector::Zen ); +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} + +default_imp_for_post_processing_steps!( + connector::Aci, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bambora, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Coinbase, + connector::Cryptopay, + connector::Dlocal, + connector::Iatapay, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Helcim, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Nexinets, + connector::Noon, + connector::Nuvei, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Shift4, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen, + connector::Adyen, + connector::Bankofamerica, + connector::Cybersource, + connector::Gocardless, + connector::Nmi, + connector::Payme, + connector::Paypal, + connector::Stripe, + connector::Trustpay, + connector::Threedsecureio +); + macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( @@ -926,6 +1034,7 @@ impl<const T: u8> api::Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -1009,6 +1118,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_create!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -1095,6 +1205,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -1178,6 +1289,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -1261,6 +1373,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Airwallex, connector::Authorizedotnet, @@ -1344,6 +1457,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1428,6 +1542,7 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1511,6 +1626,7 @@ impl<const T: u8> default_imp_for_approve!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1595,6 +1711,7 @@ impl<const T: u8> default_imp_for_reject!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1663,6 +1780,7 @@ impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} default_imp_for_fraud_check!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1747,6 +1865,7 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_sale!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1831,6 +1950,7 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_checkout!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1915,6 +2035,7 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_transaction!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -1999,6 +2120,7 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -2083,6 +2205,7 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_record_return!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -2165,6 +2288,7 @@ impl<const T: u8> default_imp_for_incremental_authorization!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -2246,6 +2370,7 @@ impl<const T: u8> } default_imp_for_revoking_mandates!( connector::Threedsecureio, + connector::Plaid, connector::Aci, connector::Adyen, connector::Airwallex, @@ -2419,5 +2544,6 @@ default_imp_for_connector_authentication!( connector::Wise, connector::Worldline, connector::Worldpay, - connector::Zen + connector::Zen, + connector::Plaid ); diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index 14b710de914..43f2f3877ce 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsApproveRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Approve, @@ -36,6 +37,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index cc2540aa221..489b3b87eaa 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -32,6 +32,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::Authorize, @@ -50,6 +51,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } @@ -179,6 +181,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu authorize_preprocessing_steps(state, &self, true, connector).await } + async fn postprocessing_steps<'a>( + self, + state: &AppState, + connector: &api::ConnectorData, + ) -> RouterResult<Self> { + authorize_postprocessing_steps(state, &self, true, connector).await + } + async fn create_connector_customer<'a>( &self, state: &AppState, @@ -368,6 +378,58 @@ pub async fn authorize_preprocessing_steps<F: Clone>( } } +pub async fn authorize_postprocessing_steps<F: Clone>( + state: &AppState, + router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + confirm: bool, + connector: &api::ConnectorData, +) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> { + if confirm { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let postprocessing_request_data = + types::PaymentsPostProcessingData::try_from(router_data.request.to_owned())?; + + let postprocessing_response_data: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let postprocessing_router_data = + payments::helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>( + router_data.clone(), + postprocessing_request_data, + postprocessing_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &postprocessing_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + + let authorize_router_data = + payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data.request.to_owned(), + resp.response, + ); + + Ok(authorize_router_data) + } else { + Ok(router_data.clone()) + } +} + impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> for types::ConnectorCustomerData { @@ -424,6 +486,29 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData } } +impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPostProcessingData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(data: types::PaymentsAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: data.payment_method_data, + amount: data.amount, + email: data.email, + currency: data.currency, + payment_method_type: data.payment_method_type, + setup_mandate_details: data.setup_mandate_details, + capture_method: data.capture_method, + order_details: data.order_details, + router_return_url: data.router_return_url, + webhook_url: data.webhook_url, + complete_authorize_url: data.complete_authorize_url, + browser_info: data.browser_info, + connector_transaction_id: data.related_transaction_id, + customer_id: data.customer_id, + }) + } +} + impl TryFrom<types::CompleteAuthorizeData> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 5918380ee0b..0a6abda11ef 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCancelRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Void, @@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index d2b7c8e91bd..4d14a188922 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCaptureRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Capture, @@ -36,6 +37,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 68d0ee8d475..c2c21569703 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -28,6 +28,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::CompleteAuthorize, @@ -46,6 +47,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index 387916bab7c..6ab6d37a3fb 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -27,6 +27,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> { Box::pin(transformers::construct_payment_router_data::< api::IncrementalAuthorization, @@ -39,6 +40,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index cb7a764985d..1f519f14dfc 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { @@ -39,6 +40,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 910cc955e63..679b7f398bd 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsRejectRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Reject, @@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index e29b66ea0ca..8a54a2a8b79 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -30,6 +30,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Session, @@ -42,6 +43,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 71d43989336..a3757975186 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -34,6 +34,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::SetupMandateRouterData> { Box::pin(transformers::construct_payment_router_data::< api::SetupMandate, @@ -46,6 +47,7 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a60fae4f579..f8917d37c4e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -49,7 +49,7 @@ use crate::{ }, storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update}, transformers::{ForeignFrom, ForeignTryFrom}, - ErrorResponse, MandateReference, RouterData, + ConnectorAuthType, ErrorResponse, MandateReference, MerchantRecipientData, RouterData, }, utils::{ self, @@ -2021,6 +2021,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBanking ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, @@ -4007,3 +4008,19 @@ pub fn validate_mandate_data_and_future_usage( Ok(()) } } + +pub fn get_recipient_id_from_open_banking_auth( + auth: &ConnectorAuthType, +) -> Result<Option<String>, errors::ApiErrorResponse> { + match auth { + ConnectorAuthType::OpenBankingAuth { + api_key: _, + key1: _, + merchant_data, + } => match merchant_data { + MerchantRecipientData::RecipientId(id) => Ok(Some(id.peek().to_string())), + _ => Err(errors::ApiErrorResponse::InternalServerError), + }, + _ => Ok(None), + } +} diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 33e8ff26edc..eae82e94d32 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -703,6 +703,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => { (None, None) } + types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None), types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list, } => match payment_data.multiple_capture_data { diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 91b6061c111..87bb22f454f 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -302,7 +302,7 @@ where ) .await?; - payments::call_connector_service( + let (router_data, _mca) = payments::call_connector_service( state, merchant_account, key_store, @@ -316,7 +316,9 @@ where api::HeaderPayload::default(), frm_suggestion, ) - .await + .await?; + + Ok(router_data) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 9dd7df66fa6..8e15e6ba61e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -29,6 +29,7 @@ use crate::{ }; #[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data<'a, F, T>( state: &'a AppState, payment_data: PaymentData<F>, @@ -37,6 +38,7 @@ pub async fn construct_payment_router_data<'a, F, T>( _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -141,7 +143,15 @@ where .payment_attempt .authentication_type .unwrap_or_default(), - connector_meta_data: merchant_connector_account.get_metadata(), + connector_meta_data: if let Some(data) = merchant_recipient_data { + let val = serde_json::to_value(data) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encoding MerchantRecipientDatas")?; + Some(masking::Secret::new(val)) + } else { + merchant_connector_account.get_metadata() + }, request: T::try_from(additional_data)?, response, amount_captured: payment_data.payment_intent.amount_captured, @@ -820,7 +830,7 @@ where { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { - payment_attempt + let condition1 = payment_attempt .connector .as_ref() .map(|connector| { @@ -835,7 +845,35 @@ where Some(false) } }) - .unwrap_or(false) + .unwrap_or(false); + + let condition2 = payment_attempt + .connector + .as_ref() + .map(|connector| matches!(connector.as_str(), "plaid")) + .and_then(|is_connector_supports_third_party_sdk| { + if is_connector_supports_third_party_sdk { + payment_attempt + .payment_method + .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::BankRedirect)) + .and_then(|first_match| { + payment_attempt + .payment_method_type + .map(|pmt| { + matches!( + pmt, + diesel_models::enums::PaymentMethodType::OpenBanking + ) + }) + .map(|second_match| first_match && second_match) + }) + } else { + Some(false) + } + }) + .unwrap_or(false); + + condition1 || condition2 } else { false } @@ -1112,6 +1150,13 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .map(|customer| customer.clone().into_inner()) }); + let customer_id = additional_data + .customer_data + .as_ref() + .map(|data| data.customer_id.clone()); + + let conn_transaction_id = payment_data.payment_attempt.connector_transaction_id; + Ok(Self { payment_method_data: payment_method_data.get_required_value("payment_method_data")?, setup_future_usage: payment_data.payment_intent.setup_future_usage, @@ -1132,12 +1177,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz order_category, session_token: None, enrolled_for_3ds: true, - related_transaction_id: None, + related_transaction_id: conn_transaction_id, payment_method_type: payment_data.payment_attempt.payment_method_type, router_return_url, webhook_url, complete_authorize_url, - customer_id: None, + customer_id, surcharge_details: payment_data.surcharge_details, request_incremental_authorization: matches!( payment_data diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 21ba27eac17..125f4b294a5 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -197,8 +197,18 @@ impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { Ok::<Self, errors::ConnectorError>(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), + merchant_data: None, }) } + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Ok::<Self, errors::ConnectorError>(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + merchant_data: Some(merchant_data.clone().into()), + }), _ => Err(errors::ConnectorError::FailedToObtainAuthType), } } diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs index 8a1369c2e02..3209ec95353 100644 --- a/crates/router/src/core/pm_auth/transformers.rs +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -2,6 +2,33 @@ use pm_auth::types::{self as pm_auth_types}; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; +impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData { + fn from(from: types::MerchantAccountData) -> Self { + match from { + types::MerchantAccountData::Iban { iban, name } => Self::Iban { iban, name }, + types::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + } => Self::Bacs { + account_number, + sort_code, + name, + }, + } + } +} + +impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData { + fn from(value: types::MerchantRecipientData) -> Self { + match value { + types::MerchantRecipientData::RecipientId(id) => Self::RecipientId(id), + types::MerchantRecipientData::WalletId(id) => Self::WalletId(id), + types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()), + } + } +} + impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType { type Error = errors::ConnectorError; fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -12,6 +39,15 @@ impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthTy secret: key1.to_owned(), }) } + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Ok::<Self, errors::ConnectorError>(Self::OpenBankingAuth { + api_key, + key1, + merchant_data: merchant_data.into(), + }), _ => Err(errors::ConnectorError::FailedToObtainAuthType), } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 5b609b072c1..76147753366 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -49,6 +49,8 @@ pub type PaymentsAuthorizeRouterData = RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<api::PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; +pub type PaymentsPostProcessingRouterData = + RouterData<api::PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = @@ -130,6 +132,11 @@ pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< PaymentsPreProcessingData, PaymentsResponseData, >; +pub type PaymentsPostProcessingType = dyn services::ConnectorIntegration< + api::PostProcessing, + PaymentsPostProcessingData, + PaymentsResponseData, +>; pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration< api::CompleteAuthorize, CompleteAuthorizeData, @@ -501,6 +508,24 @@ pub struct PaymentsPreProcessingData { pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, } +#[derive(Debug, Clone)] +pub struct PaymentsPostProcessingData { + pub payment_method_data: payments::PaymentMethodData, + pub amount: i64, + pub email: Option<Email>, + pub customer_id: Option<String>, + pub currency: storage_enums::Currency, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub setup_mandate_details: Option<MandateData>, + pub capture_method: Option<storage_enums::CaptureMethod>, + pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, + pub router_return_url: Option<String>, + pub webhook_url: Option<String>, + pub complete_authorize_url: Option<String>, + pub browser_info: Option<BrowserInformation>, + pub connector_transaction_id: Option<String>, +} + #[derive(Debug, Clone)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<payments::PaymentMethodData>, @@ -931,6 +956,9 @@ pub enum PaymentsResponseData { error_code: Option<String>, error_message: Option<String>, }, + PostProcessingResponse { + session_token: Option<api::OpenBankingSessionToken>, + }, } #[derive(Debug, Clone)] @@ -1150,6 +1178,88 @@ pub struct MandateRevokeResponseData { pub mandate_status: MandateStatus, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantAccountData { + Iban { + iban: Secret<String>, + name: String, + }, + Bacs { + account_number: Secret<String>, + sort_code: Secret<String>, + name: String, + }, +} + +impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData { + fn foreign_from(from: MerchantAccountData) -> Self { + match from { + MerchantAccountData::Iban { iban, name } => Self::Iban { iban, name }, + MerchantAccountData::Bacs { + account_number, + sort_code, + name, + } => Self::Bacs { + account_number, + sort_code, + name, + }, + } + } +} + +impl From<api_models::admin::MerchantAccountData> for MerchantAccountData { + fn from(from: api_models::admin::MerchantAccountData) -> Self { + match from { + api_models::admin::MerchantAccountData::Iban { iban, name } => { + Self::Iban { iban, name } + } + api_models::admin::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + } => Self::Bacs { + account_number, + sort_code, + name, + }, + } + } +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantRecipientData { + RecipientId(Secret<String>), + WalletId(Secret<String>), + AccountData(MerchantAccountData), +} + +impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData { + fn foreign_from(value: MerchantRecipientData) -> Self { + match value { + MerchantRecipientData::RecipientId(id) => Self::RecipientId(id), + MerchantRecipientData::WalletId(id) => Self::WalletId(id), + MerchantRecipientData::AccountData(data) => { + Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data)) + } + } + } +} + +impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData { + fn from(value: api_models::admin::MerchantRecipientData) -> Self { + match value { + api_models::admin::MerchantRecipientData::RecipientId(id) => Self::RecipientId(id), + api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id), + api_models::admin::MerchantRecipientData::AccountData(data) => { + Self::AccountData(data.into()) + } + } + } +} + // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] @@ -1176,6 +1286,11 @@ pub enum ConnectorAuthType { CurrencyAuthKey { auth_key_map: HashMap<storage_enums::Currency, pii::SecretSerdeValue>, }, + OpenBankingAuth { + api_key: Secret<String>, + key1: Secret<String>, + merchant_data: MerchantRecipientData, + }, #[default] NoKey, } @@ -1214,6 +1329,15 @@ impl From<api_models::admin::ConnectorAuthType> for ConnectorAuthType { Self::CurrencyAuthKey { auth_key_map } } api_models::admin::ConnectorAuthType::NoKey => Self::NoKey, + api_models::admin::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Self::OpenBankingAuth { + api_key, + key1, + merchant_data: merchant_data.into(), + }, } } } @@ -1248,6 +1372,17 @@ impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType { Self::CurrencyAuthKey { auth_key_map } } ConnectorAuthType::NoKey => Self::NoKey, + ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Self::OpenBankingAuth { + api_key, + key1, + merchant_data: api_models::admin::MerchantRecipientData::foreign_from( + merchant_data, + ), + }, } } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 50d256b034b..786228ba484 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -363,6 +363,7 @@ impl ConnectorData { enums::Connector::Payme => Ok(Box::new(&connector::Payme)), enums::Connector::Payu => Ok(Box::new(&connector::Payu)), enums::Connector::Placetopay => Ok(Box::new(&connector::Placetopay)), + enums::Connector::Plaid => Ok(Box::new(&connector::Plaid)), enums::Connector::Powertranz => Ok(Box::new(&connector::Powertranz)), enums::Connector::Prophetpay => Ok(Box::new(&connector::Prophetpay)), enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)), @@ -381,7 +382,6 @@ impl ConnectorData { enums::Connector::Volt => Ok(Box::new(&connector::Volt)), enums::Connector::Zen => Ok(Box::new(&connector::Zen)), enums::Connector::Signifyd - | enums::Connector::Plaid | enums::Connector::Riskified | enums::Connector::Threedsecureio => { Err(report!(errors::ConnectorError::InvalidConnectorName) diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 8e13f6c9935..48164e94000 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -2,16 +2,16 @@ pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate, - PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, - PaymentListFilters, PaymentListResponse, PaymentListResponseV2, PaymentMethodData, - PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, - PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest, - PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, + OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, + PaymentListFilterConstraints, PaymentListFilters, PaymentListResponse, PaymentListResponseV2, + PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, + PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, + PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, - PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, TimeRange, UrlDetails, - VerifyRequest, VerifyResponse, WalletData, + PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, SessionTokenType, + TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData, }; use error_stack::{IntoReport, ResultExt}; @@ -83,6 +83,9 @@ pub struct SetupMandate; #[derive(Debug, Clone)] pub struct PreProcessing; +#[derive(Debug, Clone)] +pub struct PostProcessing; + #[derive(Debug, Clone)] pub struct IncrementalAuthorization; @@ -214,6 +217,15 @@ pub trait PaymentsPreProcessing: { } +pub trait PaymentsPostProcessing: + api::ConnectorIntegration< + PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, +> +{ +} + pub trait Payment: api_types::ConnectorCommon + api_types::ConnectorValidation @@ -228,6 +240,7 @@ pub trait Payment: + PaymentSession + PaymentToken + PaymentsPreProcessing + + PaymentsPostProcessing + ConnectorCustomer + PaymentIncrementalAuthorization { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 29f924fc65b..3c0b424c94c 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -216,12 +216,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Paypal => Self::Paypal, api_enums::Connector::Payu => Self::Payu, api_models::enums::Connector::Placetopay => Self::Placetopay, - api_enums::Connector::Plaid => { - Err(common_utils::errors::ValidationError::InvalidValue { - message: "plaid is not a routable connector".to_string(), - }) - .into_report()? - } + api_enums::Connector::Plaid => Self::Plaid, api_enums::Connector::Powertranz => Self::Powertranz, api_enums::Connector::Prophetpay => Self::Prophetpay, api_enums::Connector::Rapyd => Self::Rapyd, @@ -417,6 +412,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBanking | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 8db743d6098..c69158bc293 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -46,6 +46,7 @@ mod payme; mod paypal; mod payu; mod placetopay; +mod plaid; mod powertranz; #[cfg(feature = "dummy_connector")] mod prophetpay; diff --git a/crates/router/tests/connectors/plaid.rs b/crates/router/tests/connectors/plaid.rs new file mode 100644 index 00000000000..d54d3cd6772 --- /dev/null +++ b/crates/router/tests/connectors/plaid.rs @@ -0,0 +1,423 @@ +use masking::Secret; +use router::{ + core::utils as core_utils, + types::{self, api, storage::enums}, +}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct PlaidTest; +impl ConnectorActions for PlaidTest {} +impl utils::Connector for PlaidTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Plaid; + types::api::ConnectorData { + connector: Box::new(&Plaid), + connector_name: types::Connector::Plaid, + get_token: types::api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .plaid + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "plaid".to_string() + } +} + +static CONNECTOR: PlaidTest = PlaidTest {}; + +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 3f78ff7f491..5e00249dc10 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -119,38 +119,38 @@ api_secret = "Application Identifier" key1 = "Business Identifier" [opayo] -api_key="API Key" +api_key = "API Key" [wise] api_key = "API Key" key1 = "Profile ID" [automation_configs] -hs_base_url="http://localhost:8080" -hs_test_browser="firefox" -chrome_profile_path="" -firefox_profile_path="" -pypl_email="" -pypl_pass="" -gmail_email="" -gmail_pass="" +hs_base_url = "http://localhost:8080" +hs_test_browser = "firefox" +chrome_profile_path = "" +firefox_profile_path = "" +pypl_email = "" +pypl_pass = "" +gmail_email = "" +gmail_pass = "" [payme] # Open api key -api_key="seller payme id" -key1="payme client key" +api_key = "seller payme id" +key1 = "payme client key" [cryptopay] api_key = "api_key" key1 = "key1" [cashtocode] -api_key="Classic PMT API Key" +api_key = "Classic PMT API Key" key1 = "Evoucher PMT API Key" [tsys] -api_key="device id" +api_key = "device id" key1 = "transaction key" api_secret = "developer id" @@ -159,31 +159,31 @@ api_key = "Partner code" key1 = "Credential code" [powertranz] -api_key="PowerTranz-PowerTranzPassword" +api_key = "PowerTranz-PowerTranzPassword" key1 = "PowerTranz-PowerTranzId" [stax] -api_key="API Key" +api_key = "API Key" [boku] -api_key="API Key" +api_key = "API Key" key1 = "transaction key" [square] -api_key="API Key" +api_key = "API Key" key1 = "transaction key" [helcim] -api_key="API Key" +api_key = "API Key" [gocardless] -api_key="API Key" +api_key = "API Key" [volt] -api_key="API Key" +api_key = "API Key" [prophetpay] -api_key="API Key" +api_key = "API Key" [bankofamerica] api_key = "MyApiKey" @@ -191,10 +191,12 @@ key1 = "Merchant id" api_secret = "Secret key" [placetopay] -api_key= "Login" -key1= "Trankey" +api_key = "Login" +key1 = "Trankey" [threedsecureio] -api_key="API Key" +api_key = "API Key" +[plaid] +api_key = "API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index a2753a2c517..c91a50fce33 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -49,6 +49,7 @@ pub struct ConnectorAuthentication { pub paypal: Option<BodyKey>, pub payu: Option<BodyKey>, pub placetopay: Option<BodyKey>, + pub plaid: Option<HeaderKey>, pub powertranz: Option<BodyKey>, pub prophetpay: Option<HeaderKey>, pub rapyd: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 98a2613f3f2..4c102aad709 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -107,6 +107,7 @@ payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" +plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" @@ -172,6 +173,7 @@ cards = [ "paypal", "payu", "placetopay", + "plaid", "powertranz", "prophetpay", "shift4", diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 4f6a4410cb8..251a0de4e81 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -16067,7 +16067,8 @@ "wise", "worldline", "worldpay", - "zen" + "zen", + "plaid" ] }, "RoutingAlgorithm": { diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 2be49d123b0..9ec7c031406 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay plaid powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-03-11T09:25:55Z
## Description <!-- Describe your changes in detail --> Webhook Implementation for Plaid ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
7391416e2473eab0474bd01bb155a9ecc96da263
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/admin.rs", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/common_enums/src/transformers.rs", "crates/euclid/src/frontend/dir/enums.rs", "crates/euclid/src/f...
juspay/hyperswitch
juspay__hyperswitch-4026
Bug: [REFACTOR] Allow deletion of default payment method for a customer if only one pm exists Currently, we don't delete the default payment method of a customer. But if only one payment method exists for a customer which is also set to default, then we should allow to delete that payment method
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index cefb0c240ec..bda7af157de 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -52,5 +52,5 @@ pub struct CustomerUpdateInternal { pub modified_at: Option<PrimitiveDateTime>, pub connector_customer: Option<serde_json::Value>, pub address_id: Option<String>, - pub default_payment_method_id: Option<String>, + pub default_payment_method_id: Option<Option<String>>, } diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs index 8f2e391df6c..a1dd40cd400 100644 --- a/crates/diesel_models/src/query/generics.rs +++ b/crates/diesel_models/src/query/generics.rs @@ -40,6 +40,7 @@ pub mod db_metrics { DeleteWithResult, UpdateWithResults, UpdateOne, + Count, } #[inline] diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index bed4d079010..a27a2ae8950 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -1,4 +1,9 @@ -use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; +use async_bb8_diesel::AsyncRunQueryDsl; +use diesel::{ + associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, + QueryDsl, Table, +}; +use error_stack::{IntoReport, ResultExt}; use super::generics; use crate::{ @@ -96,6 +101,34 @@ impl PaymentMethod { .await } + pub async fn get_count_by_customer_id_merchant_id_status( + conn: &PgPooledConn, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> StorageResult<i64> { + let filter = <Self as HasTable>::table() + .count() + .filter( + dsl::customer_id + .eq(customer_id.to_owned()) + .and(dsl::merchant_id.eq(merchant_id.to_owned())) + .and(dsl::status.eq(status.to_owned())), + ) + .into_boxed(); + + router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); + + generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + filter.get_result_async::<i64>(conn), + generics::db_metrics::DatabaseOperation::Count, + ) + .await + .into_report() + .change_context(errors::DatabaseError::Others) + .attach_printable("Failed to get a count of payment methods") + } + pub async fn find_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &str, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index fccacfef45d..ad272860717 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3193,7 +3193,7 @@ pub async fn set_default_payment_method( )?; let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod { - default_payment_method_id: Some(payment_method_id.to_owned()), + default_payment_method_id: Some(Some(payment_method_id.to_owned())), }; // update the db with the default payment method id @@ -3442,6 +3442,16 @@ pub async fn delete_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + let payment_methods_count = db + .get_payment_method_count_by_customer_id_merchant_id_status( + &key.customer_id, + &merchant_account.merchant_id, + api_enums::PaymentMethodStatus::Active, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get a count of payment methods for a customer")?; + let customer = db .find_customer_by_customer_id_merchant_id( &key.customer_id, @@ -3453,7 +3463,8 @@ pub async fn delete_payment_method( .attach_printable("Customer not found for the payment method")?; utils::when( - customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id), + customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) + && payment_methods_count > 1, || Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed), )?; @@ -3481,6 +3492,22 @@ pub async fn delete_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) { + let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod { + default_payment_method_id: Some(None), + }; + + db.update_customer_by_customer_id_merchant_id( + key.customer_id, + key.merchant_id, + customer_update, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the default payment method id for the customer")?; + }; + Ok(services::ApplicationResponse::Json( api::PaymentMethodDeleteResponse { payment_method_id: key.payment_method_id, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 4509da8f0ff..ff036320098 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1299,6 +1299,21 @@ impl PaymentMethodInterface for KafkaStore { .await } + async fn get_payment_method_count_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + self.diesel_store + .get_payment_method_count_by_customer_id_merchant_id_status( + customer_id, + merchant_id, + status, + ) + .await + } + async fn find_payment_method_by_locker_id( &self, locker_id: &str, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index ef471fbd246..94ebee17893 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -36,6 +36,13 @@ pub trait PaymentMethodInterface { limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; + async fn get_payment_method_count_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError>; + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -80,6 +87,25 @@ impl PaymentMethodInterface for Store { .into_report() } + #[instrument(skip_all)] + async fn get_payment_method_count_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::PaymentMethod::get_count_by_customer_id_merchant_id_status( + &conn, + customer_id, + merchant_id, + status, + ) + .await + .map_err(Into::into) + .into_report() + } + #[instrument(skip_all)] async fn insert_payment_method( &self, @@ -204,6 +230,27 @@ impl PaymentMethodInterface for MockDb { } } + async fn get_payment_method_count_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + let payment_methods = self.payment_methods.lock().await; + let count = payment_methods + .iter() + .filter(|pm| { + pm.customer_id == customer_id + && pm.merchant_id == merchant_id + && pm.status == status + }) + .count(); + count + .try_into() + .into_report() + .change_context(errors::StorageError::MockDbError) + } + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index 5437d06a2e6..d5f05944d6c 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -118,7 +118,7 @@ pub enum CustomerUpdate { connector_customer: Option<serde_json::Value>, }, UpdateDefaultPaymentMethod { - default_payment_method_id: Option<String>, + default_payment_method_id: Option<Option<String>>, }, }
2024-03-08T19:02:18Z
## Description <!-- Describe your changes in detail --> Currently, we don't delete the default payment method of a customer. But if only one payment method exists for a customer which is also set to default, then we should allow to delete that payment method ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Store a new card or any other payment method for a customer. (Ensure only one payment method exists for a customer) 2. Set that payment method as default ``` curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 3. Now try to delete that default payment method ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \ --header 'Accept: application/json' \ --header 'api-key: abc' ``` You should still be able to delete the default payment method as this is the only payment method that exists for that customer.
f5697f372c8e1f27c00f7dd120dc7813bf0e0e8a
1. Store a new card or any other payment method for a customer. (Ensure only one payment method exists for a customer) 2. Set that payment method as default ``` curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 3. Now try to delete that default payment method ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \ --header 'Accept: application/json' \ --header 'api-key: abc' ``` You should still be able to delete the default payment method as this is the only payment method that exists for that customer.
[ "crates/diesel_models/src/customers.rs", "crates/diesel_models/src/query/generics.rs", "crates/diesel_models/src/query/payment_method.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/payment_method.rs", "crates/router/src/types/domain/c...
juspay/hyperswitch
juspay__hyperswitch-3992
Bug: Create a merchant config for enable `pg_agnostic_mit` Create a merchant config (`pg_agnostic_mit`) to enable usage of Network Transaction/Reference ID in recurring mandate payments. This will be a `business profile` level config that a merchant specifies. **API Spec:-** ``` POST /business_profile/{bp_id}/configs/pg_agnostic_mit { “enabled”: true, } ```
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 4d32f1d0f81..723e6eccc36 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -11,7 +11,7 @@ pub use euclid::{ use serde::{Deserialize, Serialize}; use utoipa::ToSchema; -use crate::enums::{self, RoutableConnectors, TransactionType}; +use crate::enums::{RoutableConnectors, TransactionType}; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] @@ -299,35 +299,13 @@ impl From<RoutableConnectorChoice> for ast::ConnectorChoice { } } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct DetailedConnectorChoice { - pub connector: RoutableConnectors, - pub business_label: Option<String>, - pub business_country: Option<enums::CountryAlpha2>, - pub business_sub_label: Option<String>, -} - -impl DetailedConnectorChoice { - pub fn get_connector_label(&self) -> Option<String> { - self.business_country - .as_ref() - .zip(self.business_label.as_ref()) - .map(|(business_country, business_label)| { - let mut base_label = format!( - "{}_{:?}_{}", - self.connector, business_country, business_label - ); - - if let Some(ref sub_label) = self.business_sub_label { - base_label.push('_'); - base_label.push_str(sub_label); - } - - base_label - }) - } + pub enabled: bool, } +impl common_utils::events::ApiEventMetric for DetailedConnectorChoice {} + #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 31825617398..bec90c51e9c 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -9,7 +9,6 @@ use api_models::{ }; #[cfg(not(feature = "business_profile_routing"))] use common_utils::ext_traits::{Encode, StringExt}; -#[cfg(not(feature = "business_profile_routing"))] use diesel_models::configs; #[cfg(feature = "business_profile_routing")] use diesel_models::routing_algorithm::RoutingAlgorithm; @@ -807,6 +806,37 @@ pub async fn retrieve_linked_routing_config( } } +pub async fn upsert_connector_agnostic_mandate_config( + state: AppState, + business_profile_id: &str, + mandate_config: routing_types::DetailedConnectorChoice, +) -> RouterResponse<routing_types::DetailedConnectorChoice> { + let key = helpers::get_pg_agnostic_mandate_config_key(business_profile_id); + + let mandate_config_str = mandate_config.enabled.to_string(); + + let find_config = state + .store + .find_config_by_key_unwrap_or(&key, Some(mandate_config_str.clone())) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error saving pg agnostic mandate config to db")?; + + if find_config.config != mandate_config_str { + let config_update = configs::ConfigUpdate::Update { + config: Some(mandate_config_str), + }; + state + .store + .update_config_by_key(&key, config_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error saving pg agnostic mandate config to db")?; + } + + Ok(service_api::ApplicationResponse::Json(mandate_config)) +} + pub async fn retrieve_default_routing_config_for_profiles( state: AppState, merchant_account: domain::MerchantAccount, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index febd1cd86dd..a725cc714e2 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -273,9 +273,9 @@ pub async fn update_business_profile_active_algorithm_ref( pub async fn get_merchant_connector_agnostic_mandate_config( db: &dyn StorageInterface, - merchant_id: &str, + business_profile_id: &str, ) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> { - let key = get_pg_agnostic_mandate_config_key(merchant_id); + let key = get_pg_agnostic_mandate_config_key(business_profile_id); let maybe_config = db.find_config_by_key(&key).await; match maybe_config { @@ -312,29 +312,6 @@ pub async fn get_merchant_connector_agnostic_mandate_config( } } -pub async fn update_merchant_connector_agnostic_mandate_config( - db: &dyn StorageInterface, - merchant_id: &str, - mandate_config: Vec<routing_types::DetailedConnectorChoice>, -) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> { - let key = get_pg_agnostic_mandate_config_key(merchant_id); - let mandate_config_str = mandate_config - .encode_to_string_of_json() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to serialize pg agnostic mandate config during update")?; - - let config_update = configs::ConfigUpdate::Update { - config: Some(mandate_config_str), - }; - - db.update_config_by_key(&key, config_update) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error saving pg agnostic mandate config to db")?; - - Ok(mandate_config) -} - pub async fn validate_connectors_in_routing_config( db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, @@ -465,8 +442,8 @@ pub fn get_routing_dictionary_key(merchant_id: &str) -> String { /// Provides the identifier for the specific merchant's agnostic_mandate_config #[inline(always)] -pub fn get_pg_agnostic_mandate_config_key(merchant_id: &str) -> String { - format!("pg_agnostic_mandate_{merchant_id}") +pub fn get_pg_agnostic_mandate_config_key(business_profile_id: &str) -> String { + format!("pg_agnostic_mandate_{business_profile_id}") } /// Provides the identifier for the specific merchant's default_config diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 01ed994a9d3..7d9ee1670dc 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -437,6 +437,10 @@ impl Routing { ) })), ) + .service( + web::resource("/business_profile/{business_profile_id}/configs/pg_agnostic_mit") + .route(web::post().to(cloud_routing::upsert_connector_agnostic_mandate_config)), + ) .service( web::resource("/default") .route(web::get().to(|state, req| { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 7908b9dfdca..02a3a6841f4 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -225,6 +225,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ReconTokenRequest | Flow::ReconServiceRequest | Flow::ReconVerifyToken => Self::Recon, + Flow::CreateConnectorAgnosticMandateConfig => Self::Routing, } } } diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 1476fc7b3d6..28d65f66a82 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -566,6 +566,44 @@ pub async fn routing_retrieve_linked_config( } } +#[cfg(feature = "olap")] +#[instrument(skip_all)] +pub async fn upsert_connector_agnostic_mandate_config( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<routing_types::DetailedConnectorChoice>, + path: web::Path<String>, +) -> impl Responder { + use crate::services::authentication::AuthenticationData; + + let flow = Flow::CreateConnectorAgnosticMandateConfig; + let business_profile_id = path.into_inner(); + + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _auth: AuthenticationData, mandate_config| { + Box::pin(routing::upsert_connector_agnostic_mandate_config( + state, + &business_profile_id, + mandate_config, + )) + }, + #[cfg(not(feature = "release"))] + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::RoutingWrite), + req.headers(), + ), + #[cfg(feature = "release")] + &auth::JWTAuth(Permission::RoutingWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn routing_retrieve_default_config_for_profiles( diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index df322da9429..ca8d75b3324 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -206,6 +206,8 @@ pub enum Flow { RoutingRetrieveConfig, /// Routing retrieve active config RoutingRetrieveActiveConfig, + /// Update connector agnostic mandate config + CreateConnectorAgnosticMandateConfig, /// Routing retrieve default config RoutingRetrieveDefaultConfig, /// Routing retrieve dictionary
2024-03-08T14:19:25Z
## Description <!-- Describe your changes in detail --> This pr adds a merchant config (`pg_agnostic_mit`) to enable usage of Network Transaction/Reference ID in recurring `MIT` payments. This will be a `business profile` level config that a merchant specifies. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Set processor agnostic MIT config as `true` <img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/76c54b6a-888c-42fc-b5b2-024eecabf868"> config status from db ![image](https://github.com/juspay/hyperswitch/assets/83439957/dbcd0961-685d-4e76-92da-48ed7da33756) Set processor agnostic MIT config as `false` <img width="654" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e0dbd263-bc26-4167-ae96-f6a65cd0730c"> config status from db ![image](https://github.com/juspay/hyperswitch/assets/83439957/632144b1-8c0f-42c6-9232-8f2c4571ba3e) ```curl curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ```
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
Set processor agnostic MIT config as `true` <img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/76c54b6a-888c-42fc-b5b2-024eecabf868"> config status from db ![image](https://github.com/juspay/hyperswitch/assets/83439957/dbcd0961-685d-4e76-92da-48ed7da33756) Set processor agnostic MIT config as `false` <img width="654" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e0dbd263-bc26-4167-ae96-f6a65cd0730c"> config status from db ![image](https://github.com/juspay/hyperswitch/assets/83439957/632144b1-8c0f-42c6-9232-8f2c4571ba3e) ```curl curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT_Token' \ --data '{ "enabled": true }' ```
[ "crates/api_models/src/routing.rs", "crates/router/src/core/routing.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/routing.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4021
Bug: [BUG] : error message is different when invalid data is passed for `payment_method_data` ### Bug Description It bugs out when invlaid card data is passed to the `payment_method_data`. The following payment method data contains invalid card number ```json { "payment_method_data": { "card": { "card_number": "1234", "card_exp_month": "10", "card_exp_year": "12", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` ### Expected Behavior The returned error should be ```json { "error": "Json deserialize error: not a valid credit card number at line 26 column 33" } ``` ### Actual Behavior The error displayed is ```json { "error": "Json deserialize error: data did not match any variant of untagged enum __Inner at line 32 column 5" } ``` ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. - Create a payment with below details ```bash curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Nb5N9Vl2KPrbKqADO1F0olvVJanZMy0gWss6NaKXk5wfC5okqOWLvQN4W7i6e8XF' \ --data-raw '{ "amount": 6969, "currency": "USD", "confirm": false, "name": "John Dough", "capture_method": "manual", "amount_to_capture": 6000, "phone": "999999999", "phone_country_code": "+65", "customer_id": "cus_PAxm0MeCGM5TowgDKPc9", "email": "example@juspay.in", "setup_future_usage": "on_session", "description": "Its my fourth payment request", "authentication_type": "no_three_ds", "routing": { "type": "single", "data": { "connector": "stripe" } }, "payment_method_data": { "card": { "card_number": "1234", "card_exp_month": "10", "card_exp_year": "12", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "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" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "statement_descriptor_name": "hola", "statement_descriptor_suffix": "JS" }' ``` ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index e5882fcb49d..dee5f2d0757 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1095,12 +1095,19 @@ mod payment_method_data_serde { #[serde(untagged)] enum __Inner { RewardString(String), - OptionalPaymentMethod(Box<PaymentMethodDataRequest>), + OptionalPaymentMethod(serde_json::Value), } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { - __Inner::OptionalPaymentMethod(value) => Ok(Some(*value)), + __Inner::OptionalPaymentMethod(value) => { + let parsed_value = serde_json::from_value::<PaymentMethodDataRequest>(value) + .map_err(|serde_json_error| { + serde::de::Error::custom(serde_json_error.to_string()) + })?; + + Ok(Some(parsed_value)) + } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, @@ -4048,3 +4055,73 @@ pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } + +#[cfg(test)] +mod payments_request_api_contract { + #![allow(clippy::unwrap_used)] + #![allow(clippy::panic)] + use std::str::FromStr; + + use super::*; + + #[test] + fn test_successful_card_deser() { + let payments_request = r#" + { + "amount": 6540, + "currency": "USD", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_number": "4242424242424242", + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + } + } + "#; + + let expected_card_number_string = "4242424242424242"; + let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); + + let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); + assert!(payments_request.is_ok()); + + if let PaymentMethodData::Card(card_data) = payments_request + .unwrap() + .payment_method_data + .unwrap() + .payment_method_data + { + assert_eq!(card_data.card_number, expected_card_number); + } else { + panic!("Received unexpected response") + } + } + + #[test] + fn test_successful_payment_method_reward() { + let payments_request = r#" + { + "amount": 6540, + "currency": "USD", + "payment_method": "reward", + "payment_method_data": "reward", + "payment_method_type": "evoucher" + } + "#; + + let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); + assert!(payments_request.is_ok()); + assert_eq!( + payments_request + .unwrap() + .payment_method_data + .unwrap() + .payment_method_data, + PaymentMethodData::Reward + ); + } +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js new file mode 100644 index 00000000000..f1c2c6af775 --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js @@ -0,0 +1,26 @@ +// Validate status 400 +pm.test("[POST]::/payments - Status code is 400", function () { + pm.response.to.be.error +}); + +// 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.test("[POST]::/payments - Response has appropriate error message", function () { + pm.expect(jsonData.error.message).eql("Invalid card_cvc length"); +}) diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json new file mode 100644 index 00000000000..77b40a8ece1 --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json @@ -0,0 +1,41 @@ +{ + "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": "USD", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_number": "4242424242424242", + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "card_cvc": "" + } + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": ["{{baseUrl}}"], + "path": ["payments"] + }, + "description": "Create a Payment to ensure api contract is intact" +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js new file mode 100644 index 00000000000..c645f670ebf --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js @@ -0,0 +1,16 @@ +// Validate status 400 +pm.test("[POST]::/payments - Status code is 400", function () { + pm.response.to.be.error +}); + +// 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(); +}); diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json new file mode 100644 index 00000000000..2cb146e30ab --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json @@ -0,0 +1,41 @@ +{ + "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": "USD", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_number": "1234", + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": ["{{baseUrl}}"], + "path": ["payments"] + }, + "description": "Create a Payment to ensure api contract is intact" +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js new file mode 100644 index 00000000000..8b3d52a3c6f --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js @@ -0,0 +1,26 @@ +// Validate status 400 +pm.test("[POST]::/payments - Status code is 400", function () { + pm.response.to.be.error +}); + +// 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.test("[POST]::/payments - Response has appropriate error message", function () { + pm.expect(jsonData.error.message).eql("Invalid Expiry Month"); +}) diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json new file mode 100644 index 00000000000..2c3d0fe427c --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json @@ -0,0 +1,41 @@ +{ + "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": "USD", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_number": "4242424242424242", + "card_exp_month": "13", + "card_exp_year": "69", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": ["{{baseUrl}}"], + "path": ["payments"] + }, + "description": "Create a Payment to ensure api contract is intact" +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js new file mode 100644 index 00000000000..cd3df41663f --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js @@ -0,0 +1,31 @@ +// Validate status 400 +pm.test("[POST]::/payments - Status code is 400", function () { + pm.response.to.be.error +}); + +// 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) { } + +if (jsonData?.error?.message) { + pm.test( + "[POST]::/payments - Content check for error message to equal `Invalid Expiry Year`", + function () { + pm.expect(jsonData.error.message).to.eql("Invalid Expiry Year"); + }, + ); +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json new file mode 100644 index 00000000000..63eda0afbe0 --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json @@ -0,0 +1,41 @@ +{ + "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": "USD", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_number": "4242424242424242", + "card_exp_month": "10", + "card_exp_year": "22", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": ["{{baseUrl}}"], + "path": ["payments"] + }, + "description": "Create a Payment to ensure api contract is intact" +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js new file mode 100644 index 00000000000..600ad2ed90b --- /dev/null +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js @@ -0,0 +1,33 @@ +// 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) { } + +// 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_confirmation'", + function () { + pm.expect(jsonData.status).to.eql("requires_confirmation"); + }, + ); +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js deleted file mode 100644 index d462b381cc6..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js +++ /dev/null @@ -1,9 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); \ No newline at end of file diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js index 0444324000a..c899ee4eb06 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js @@ -19,53 +19,14 @@ pm.test("[POST]::/payments - Response has JSON Body", function () { 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.", - ); -} +} catch (e) { } // 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'", + "[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'", function () { - pm.expect(jsonData.status).to.eql("requires_payment_method"); + pm.expect(jsonData.status).to.eql("requires_confirmation"); }, ); } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json index e5797a68e1b..52c5f911094 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json @@ -19,7 +19,10 @@ }, "raw_json_formatted": { "amount": 6540, - "currency": "USD" + "currency": "USD", + "payment_method": "reward", + "payment_method_type": "evoucher", + "payment_method_data": "reward" } }, "url": { diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 497d1c3669d..c3d6371fd7d 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -21800,21 +21800,39 @@ "name": "Scenario32-Ensure API Contract for Payment Method Data", "item": [ { - "name": "Payments - Card Payment Method", + "name": "Payments - Card Payment Method Invalid Card CVC", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 400", + "pm.test(\"[POST]::/payments - Status code is 400\", function () {", + " pm.response.to.be.error", + "});", + "", + "// 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.test(\"[POST]::/payments - Response has appropriate error message\", function () {", + " pm.expect(jsonData.error.message).eql(\"Invalid card_cvc length\");", + "})", + "" ], "type": "text/javascript" } @@ -21839,7 +21857,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"\"}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -21854,15 +21872,77 @@ } }, { - "name": "Payments - Reward Payment Method", + "name": "Payments - Card Payment Method Invalid Card Number", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 400", + "pm.test(\"[POST]::/payments - Status code is 400\", function () {", + " pm.response.to.be.error", + "});", + "", + "// 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();", + "});", + "" + ], + "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\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"1234\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "Create a Payment to ensure api contract is intact" + } + }, + { + "name": "Payments - Card Payment Method Invalid Expiry month", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 400", + "pm.test(\"[POST]::/payments - Status code is 400\", function () {", + " pm.response.to.be.error", "});", "", "// Validate if response header has matching content-type", @@ -21881,53 +21961,242 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) {}", + "} 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,", + "pm.test(\"[POST]::/payments - Response has appropriate error message\", function () {", + " pm.expect(jsonData.error.message).eql(\"Invalid Expiry Month\");", + "})", + "" + ], + "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\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"13\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "Create a Payment to ensure api contract is intact" + } + }, + { + "name": "Payments - Card Payment Method Invalid Expiry year", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 400", + "pm.test(\"[POST]::/payments - Status code is 400\", function () {", + " pm.response.to.be.error", + "});", + "", + "// 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\",", " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + "});", + "", + "// 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) { }", + "", + "if (jsonData?.error?.message) {", + " pm.test(", + " \"[POST]::/payments - Content check for error message to equal `Invalid Expiry Year`\",", + " function () {", + " pm.expect(jsonData.error.message).to.eql(\"Invalid Expiry Year\");", + " },", " );", "}", + "" + ], + "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\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"22\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "Create a Payment to ensure api contract is intact" + } + }, + { + "name": "Payments - Card Payment Method Success", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", "", - "// 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,", + "// 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\",", " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + "});", + "", + "// 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) { }", + "", + "// 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_confirmation'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " },", " );", "}", + "" + ], + "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\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "Create a Payment to ensure api contract is intact" + } + }, + { + "name": "Payments - Reward Payment Method", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", "", - "// 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.\",", + "// 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) { }", "", "// 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'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", " },", " );", "}", @@ -21956,7 +22225,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\"}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"reward\",\"payment_method_type\":\"evoucher\",\"payment_method_data\":\"reward\"}" }, "url": { "raw": "{{baseUrl}}/payments",
2024-03-08T12:24:17Z
## Description <!-- Describe your changes in detail --> If any invalid payment method data is passed, the error we received was wrong. This PR fixes it. More context can be found in the linked issue. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Postman and unit test cases.
f5697f372c8e1f27c00f7dd120dc7813bf0e0e8a
- Postman and unit test cases.
[ "crates/api_models/src/payments.rs", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data...
juspay/hyperswitch
juspay__hyperswitch-3950
Bug: [REFACTOR] handle payment method duplication in payouts Currently, when same payment method is saved in payouts, duplication logic is not handled. Locker returns `duplication_check` based on which duplication of payment methods has to be handled in Hyperswitch. This issue similar to https://github.com/juspay/hyperswitch/issues/3147
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index f639aa59218..357f077332d 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -27,6 +27,15 @@ pub enum StoreLockerReq<'a> { LockerGeneric(StoreGenericReq<'a>), } +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, + Self::LockerGeneric(_) => (), + } + } +} + #[derive(Debug, Deserialize, Serialize)] pub struct StoreCardReq<'a> { pub merchant_id: &'a str, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 566caa7acc5..04c80cc6267 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1337,7 +1337,10 @@ pub async fn fulfill_payout( .status .unwrap_or(payout_attempt.status.to_owned()); payout_data.payouts.status = status; - if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.is_none() { + if payout_data.payouts.recurring + && payout_data.payouts.payout_method_id.is_none() + && !helpers::is_payout_err_state(status) + { helpers::save_payout_data_to_locker( state, payout_data, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 6efe6ee9a77..5681999ae9f 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,4 +1,4 @@ -use api_models::enums::PayoutConnectors; +use api_models::{enums, payouts}; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, StringExt}, @@ -11,10 +11,12 @@ use router_env::logger; use super::PayoutData; use crate::{ core::{ - errors::{self, RouterResult}, + errors::{self, RouterResult, StorageErrorExt}, payment_methods::{ cards, - transformers::{self, StoreCardReq, StoreGenericReq, StoreLockerReq}, + transformers::{ + self, DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq, + }, vault, }, payments::{ @@ -191,9 +193,9 @@ pub async fn save_payout_data_to_locker( key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt; - let (locker_req, card_details, bank_details, wallet_details, payment_method_type) = + let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) = match payout_method_data { - api_models::payouts::PayoutMethodData::Card(card) => { + payouts::PayoutMethodData::Card(card) => { let card_detail = api::CardDetail { card_number: card.card_number.to_owned(), card_holder_name: card.card_holder_name.to_owned(), @@ -206,7 +208,7 @@ pub async fn save_payout_data_to_locker( card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { - merchant_id: &merchant_account.merchant_id, + merchant_id: merchant_account.merchant_id.as_ref(), merchant_customer_id: payout_attempt.customer_id.to_owned(), card: transformers::Card { card_number: card.card_number.to_owned(), @@ -250,31 +252,32 @@ pub async fn save_payout_data_to_locker( Ok(hex::encode(e.peek())) })?; let payload = StoreLockerReq::LockerGeneric(StoreGenericReq { - merchant_id: &merchant_account.merchant_id, + merchant_id: merchant_account.merchant_id.as_ref(), merchant_customer_id: payout_attempt.customer_id.to_owned(), enc_data, }); match payout_method_data { - api_models::payouts::PayoutMethodData::Bank(bank) => ( + payouts::PayoutMethodData::Bank(bank) => ( payload, None, Some(bank.to_owned()), None, api_enums::PaymentMethodType::foreign_from(bank.to_owned()), ), - api_models::payouts::PayoutMethodData::Wallet(wallet) => ( + payouts::PayoutMethodData::Wallet(wallet) => ( payload, None, None, Some(wallet.to_owned()), api_enums::PaymentMethodType::foreign_from(wallet.to_owned()), ), - api_models::payouts::PayoutMethodData::Card(_) => { + payouts::PayoutMethodData::Card(_) => { Err(errors::ApiErrorResponse::InternalServerError)? } } } }; + // Store payout method in locker let stored_resp = cards::call_to_locker_hs( state, @@ -285,113 +288,272 @@ pub async fn save_payout_data_to_locker( .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - // Store card_reference in payouts table let db = &*state.store; - let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate { - payout_method_id: Some(stored_resp.card_reference.to_owned()), + + // Handle duplicates + let (should_insert_in_pm_table, metadata_update) = match stored_resp.duplication_check { + // Check if equivalent entry exists in payment_methods + Some(duplication_check) => { + let locker_ref = stored_resp.card_reference.clone(); + + // Use locker ref as payment_method_id + let existing_pm_by_pmid = db.find_payment_method(&locker_ref).await; + + match existing_pm_by_pmid { + // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_method's table + Ok(pm) => ( + false, + if duplication_check == DataDuplicationCheck::MetaDataChanged { + Some(pm.clone()) + } else { + None + }, + ), + + // If not found, use locker ref as locker_id + Err(err) => { + if err.current_context().is_db_not_found() { + match db.find_payment_method_by_locker_id(&locker_ref).await { + // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_methods table + Ok(pm) => ( + false, + if duplication_check == DataDuplicationCheck::MetaDataChanged { + Some(pm.clone()) + } else { + None + }, + ), + Err(err) => { + // If not found, update locker's metadata [DELETE + INSERT OP], and insert in payment_methods table + if err.current_context().is_db_not_found() { + (true, None) + + // Misc. DB errors + } else { + Err(err) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "DB failures while finding payment method by locker ID", + )? + } + } + } + // Misc. DB errors + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("DB failures while finding payment method by pm ID")? + } + } + } + } + + // Not duplicate, should be inserted in payment_methods table + None => (true, None), }; - db.update_payout( - &payout_data.payouts, - updated_payout, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error updating payouts in saved payout method")?; - // fetch card info from db - let card_isin = card_details - .as_ref() - .map(|c| c.card_number.clone().get_card_isin()); + // Form payment method entry and card's metadata whenever insertion or metadata update is required + let (card_details_encrypted, new_payment_method) = + if let (api::PayoutMethodData::Card(_), true, _) + | (api::PayoutMethodData::Card(_), _, Some(_)) = ( + payout_method_data, + should_insert_in_pm_table, + metadata_update.as_ref(), + ) { + // Fetch card info from db + let card_isin = card_details + .as_ref() + .map(|c| c.card_number.clone().get_card_isin()); + + let mut payment_method = api::PaymentMethodCreate { + payment_method: api_enums::PaymentMethod::foreign_from( + payout_method_data.to_owned(), + ), + payment_method_type: Some(payment_method_type), + payment_method_issuer: None, + payment_method_issuer_code: None, + bank_transfer: None, + card: card_details.clone(), + wallet: None, + metadata: None, + customer_id: Some(payout_attempt.customer_id.to_owned()), + card_network: None, + }; - let pm_data = card_isin - .clone() - .async_and_then(|card_isin| async move { - db.get_card_info(&card_isin) + let pm_data = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) .await - .map_err(|error| services::logger::warn!(card_info_error=?error)) - .ok() - }) - .await - .flatten() - .map(|card_info| { - api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: card_info.card_issuing_country, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - - card_isin: card_isin.clone(), - card_issuer: card_info.card_issuer, - card_network: card_info.card_network, - card_type: card_info.card_type, - saved_to_locker: true, - }, + .flatten() + .map(|card_info| { + payment_method.payment_method_issuer = card_info.card_issuer.clone(); + payment_method.card_network = + card_info.card_network.clone().map(|cn| cn.to_string()); + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: card_info.card_issuing_country, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: card_info.card_issuer, + card_network: card_info.card_network, + card_type: card_info.card_type, + saved_to_locker: true, + }, + ) + }) + .unwrap_or_else(|| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, + }, + ) + }); + ( + cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await, + payment_method, ) - }) - .unwrap_or_else(|| { - api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: None, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - - card_isin: card_isin.clone(), - card_issuer: None, + } else { + ( + None, + api::PaymentMethodCreate { + payment_method: api_enums::PaymentMethod::foreign_from( + payout_method_data.to_owned(), + ), + payment_method_type: Some(payment_method_type), + payment_method_issuer: None, + payment_method_issuer_code: None, + bank_transfer: bank_details, + card: None, + wallet: wallet_details, + metadata: None, + customer_id: Some(payout_attempt.customer_id.to_owned()), card_network: None, - card_type: None, - saved_to_locker: true, }, ) - }); - - let card_details_encrypted = - cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; - - // Insert in payment_method table - let payment_method = api::PaymentMethodCreate { - payment_method: api_enums::PaymentMethod::foreign_from(payout_method_data.to_owned()), - payment_method_type: Some(payment_method_type), - payment_method_issuer: None, - payment_method_issuer_code: None, - bank_transfer: bank_details, - card: card_details, - wallet: wallet_details, - metadata: None, - customer_id: Some(payout_attempt.customer_id.to_owned()), - card_network: None, + }; + + // Insert new entry in payment_methods table + if should_insert_in_pm_table { + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + cards::create_payment_method( + db, + &new_payment_method, + &payout_attempt.customer_id, + &payment_method_id, + Some(stored_resp.card_reference.clone()), + &merchant_account.merchant_id, + None, + None, + card_details_encrypted.clone(), + key_store, + None, + None, + ) + .await?; + } + + /* 1. Delete from locker + * 2. Create new entry in locker + * 3. Handle creation response from locker + * 4. Update card's metadata in payment_methods table + */ + if let Some(existing_pm) = metadata_update { + let card_reference = &existing_pm + .locker_id + .clone() + .unwrap_or(existing_pm.payment_method_id.clone()); + // Delete from locker + cards::delete_card_from_hs_locker( + state, + &payout_attempt.customer_id, + &merchant_account.merchant_id, + card_reference, + ) + .await + .attach_printable( + "Failed to delete PMD from locker as a part of metadata update operation", + )?; + + locker_req.update_requestor_card_reference(Some(card_reference.to_string())); + + // Store in locker + let stored_resp = cards::call_to_locker_hs( + state, + &locker_req, + &payout_attempt.customer_id, + api_enums::LockerChoice::HyperswitchCardVault, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError); + + // Check if locker operation was successful or not, if not, delete the entry from payment_methods table + 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, + &existing_pm.payment_method_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + Err(errors::ApiErrorResponse::InternalServerError).attach_printable( + "Failed to insert PMD from locker as a part of metadata update operation", + )? + }; + + // Update card's metadata in payment_methods table + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: card_details_encrypted, + }; + db.update_payment_method(existing_pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; }; - let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); - cards::create_payment_method( - db, - &payment_method, - &payout_attempt.customer_id, - &payment_method_id, - Some(stored_resp.card_reference), - &merchant_account.merchant_id, - None, - None, - card_details_encrypted, - key_store, - None, - None, + // Store card_reference in payouts table + let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate { + payout_method_id: Some(stored_resp.card_reference.to_owned()), + }; + db.update_payout( + &payout_data.payouts, + updated_payout, + merchant_account.storage_scheme, ) - .await?; + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payouts in saved payout method")?; Ok(()) } @@ -626,7 +788,7 @@ pub fn should_call_payout_connector_create_customer<'a>( connector_label: &str, ) -> (bool, Option<&'a str>) { // Check if create customer is required for the connector - match PayoutConnectors::try_from(connector.connector_name) { + match enums::PayoutConnectors::try_from(connector.connector_name) { Ok(connector) => { let connector_needs_customer = state .conf
2024-03-07T16:47:54Z
## Description Explained in #3950 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? _**Note -** DM for postman collection_ ![image](https://github.com/juspay/hyperswitch/assets/46213975/a5fe810a-3a32-48dc-a07a-018f77381ea1) For ensuring card duplication is handled in payouts flow, we use below procedure (assuming merchant accounts and connector accounts are created) - Create a new customer - Save a card for this customer using /payment_methods endpoint - Create a new payout for this customer using the same card number - Payouts flow would try to persist these details in locker - **Test # 1** - listing customer's PMs should return a single PM - Create a new payout using SPM - Payout flow would try to persist these details again - **Test # 2** - listing customer's PMs should return a single PM - Try to save the same card details for this user using /payment_methods again - **Test # 3** - listing customer's PMs should return a single PM Above test cases are present in postman collection.
21e2d78117a9e25708b8c6a2280f6a836ee86072
_**Note -** DM for postman collection_ ![image](https://github.com/juspay/hyperswitch/assets/46213975/a5fe810a-3a32-48dc-a07a-018f77381ea1) For ensuring card duplication is handled in payouts flow, we use below procedure (assuming merchant accounts and connector accounts are created) - Create a new customer - Save a card for this customer using /payment_methods endpoint - Create a new payout for this customer using the same card number - Payouts flow would try to persist these details in locker - **Test # 1** - listing customer's PMs should return a single PM - Create a new payout using SPM - Payout flow would try to persist these details again - **Test # 2** - listing customer's PMs should return a single PM - Try to save the same card details for this user using /payment_methods again - **Test # 3** - listing customer's PMs should return a single PM Above test cases are present in postman collection.
[ "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/payouts.rs", "crates/router/src/core/payouts/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3890
Bug: Routing changes to choose between MIT details and raw card Will have to be extended in future to choose between MIT details vs Network Reference ID as well
diff --git a/config/development.toml b/config/development.toml index 6d4914af8b4..6e27e110ee9 100644 --- a/config/development.toml +++ b/config/development.toml @@ -581,4 +581,4 @@ enabled = true file_storage_backend = "file_system" [unmasked_headers] -keys = "user-agent" \ No newline at end of file +keys = "user-agent" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6f97a87fbe9..33d355d255a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -740,7 +740,7 @@ pub enum MandateTransactionType { #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { - pub mandate_id: String, + pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } @@ -767,7 +767,7 @@ pub struct UpdateHistory { impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { - mandate_id, + mandate_id: Some(mandate_id), mandate_reference_id: None, } } diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 5eb682d4cfa..c1b8731ee89 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -139,7 +139,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP .request .mandate_id .as_ref() - .map(|ids| ids.mandate_id.clone()), + .and_then(|ids| ids.mandate_id.clone()), // [#595[FEATURE] Pass Mandate history information in payment flows/request] installments: item .router_data diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index d07a8814c88..2838edfbf91 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -326,48 +326,52 @@ where Err(_) => {} Ok(_) => match resp.request.get_mandate_id() { Some(mandate_id) => { - let mandate_id = &mandate_id.mandate_id; - let mandate = state - .store - .find_mandate_by_merchant_id_mandate_id(resp.merchant_id.as_ref(), mandate_id) - .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - let mandate = match mandate.mandate_type { - storage_enums::MandateType::SingleUse => state + if let Some(ref mandate_id) = mandate_id.mandate_id { + let mandate = state .store - .update_mandate_by_merchant_id_mandate_id( - &resp.merchant_id, + .find_mandate_by_merchant_id_mandate_id( + resp.merchant_id.as_ref(), mandate_id, - storage::MandateUpdate::StatusUpdate { - mandate_status: storage_enums::MandateStatus::Revoked, - }, ) .await - .change_context(errors::ApiErrorResponse::MandateUpdateFailed), - storage_enums::MandateType::MultiUse => state - .store - .update_mandate_by_merchant_id_mandate_id( - &resp.merchant_id, - mandate_id, - storage::MandateUpdate::CaptureAmountUpdate { - amount_captured: Some( - mandate.amount_captured.unwrap_or(0) - + resp.request.get_amount(), - ), - }, - ) - .await - .change_context(errors::ApiErrorResponse::MandateUpdateFailed), - }?; - metrics::SUBSEQUENT_MANDATE_PAYMENT.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes( - "connector", - mandate.connector, - )], - ); - resp.payment_method_id = Some(mandate.payment_method_id); + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + let mandate = match mandate.mandate_type { + storage_enums::MandateType::SingleUse => state + .store + .update_mandate_by_merchant_id_mandate_id( + &resp.merchant_id, + mandate_id, + storage::MandateUpdate::StatusUpdate { + mandate_status: storage_enums::MandateStatus::Revoked, + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateUpdateFailed), + storage_enums::MandateType::MultiUse => state + .store + .update_mandate_by_merchant_id_mandate_id( + &resp.merchant_id, + mandate_id, + storage::MandateUpdate::CaptureAmountUpdate { + amount_captured: Some( + mandate.amount_captured.unwrap_or(0) + + resp.request.get_amount(), + ), + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateUpdateFailed), + }?; + metrics::SUBSEQUENT_MANDATE_PAYMENT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + mandate.connector, + )], + ); + resp.payment_method_id = Some(mandate.payment_method_id); + } } None => { if resp.request.get_setup_mandate_details().is_some() { @@ -409,7 +413,7 @@ where logger::debug!("{:?}", new_mandate_data); resp.request .set_mandate_id(Some(api_models::payments::MandateIds { - mandate_id: new_mandate_data.mandate_id.clone(), + mandate_id: Some(new_mandate_data.mandate_id.clone()), mandate_reference_id: new_mandate_data .connector_mandate_ids .clone() diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ca3bbfd0651..2544bffda72 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -13,7 +13,10 @@ pub mod types; use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter}; -use api_models::{self, enums, payments::HeaderPayload}; +use api_models::{ + self, enums, + payments::{self as payments_api, HeaderPayload}, +}; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; @@ -2061,9 +2064,11 @@ where pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, + pub token_data: Option<storage::PaymentTokenData>, pub confirm: Option<bool>, pub force_sync: Option<bool>, pub payment_method_data: Option<api::PaymentMethodData>, + pub payment_method_info: Option<storage::PaymentMethod>, pub refunds: Vec<storage::Refund>, pub disputes: Vec<storage::Dispute>, pub attempts: Option<Vec<storage::PaymentAttempt>>, @@ -2652,7 +2657,10 @@ where .as_ref() .zip(payment_data.payment_attempt.payment_method_type.as_ref()) { - if let Some(choice) = pre_routing_results.get(storage_pm_type) { + if let (Some(choice), None) = ( + pre_routing_results.get(storage_pm_type), + &payment_data.token_data, + ) { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &choice.connector.to_string(), @@ -2687,6 +2695,12 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { + #[cfg(feature = "business_profile_routing")] + let profile_id = payment_data.payment_intent.profile_id.clone(); + + #[cfg(not(feature = "business_profile_routing"))] + let _profile_id: Option<String> = None; + connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, @@ -2695,20 +2709,13 @@ where &TransactionData::Payment(payment_data), eligible_connectors, #[cfg(feature = "business_profile_routing")] - payment_data.payment_intent.profile_id.clone(), + profile_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } - let first_connector_choice = connectors - .first() - .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .into_report() - .attach_printable("Empty connector list returned")? - .clone(); - let connector_data = connectors .into_iter() .map(|conn| { @@ -2726,17 +2733,11 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - routing_data.routed_through = Some(first_connector_choice.connector.to_string()); - #[cfg(feature = "connector_choice_mca_id")] - { - routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; - } - #[cfg(not(feature = "connector_choice_mca_id"))] - { - routing_data.business_sub_label = first_connector_choice.sub_label.clone(); - } - routing_data.routing_info.algorithm = Some(routing_algorithm); - return Ok(api::ConnectorCallType::Retryable(connector_data)); + return decide_connector_for_token_based_mit_flow( + payment_data, + routing_data, + connector_data, + ); } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { @@ -2748,6 +2749,12 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { + #[cfg(feature = "business_profile_routing")] + let profile_id = payment_data.payment_intent.profile_id.clone(); + + #[cfg(not(feature = "business_profile_routing"))] + let _profile_id: Option<String> = None; + connectors = routing::perform_eligibility_analysis_with_fallback( &state, key_store, @@ -2756,20 +2763,13 @@ where &TransactionData::Payment(payment_data), eligible_connectors, #[cfg(feature = "business_profile_routing")] - payment_data.payment_intent.profile_id.clone(), + profile_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } - let first_connector_choice = connectors - .first() - .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .into_report() - .attach_printable("Empty connector list returned")? - .clone(); - let connector_data = connectors .into_iter() .map(|conn| { @@ -2787,16 +2787,11 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - routing_data.routed_through = Some(first_connector_choice.connector.to_string()); - #[cfg(feature = "connector_choice_mca_id")] - { - routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; - } - #[cfg(not(feature = "connector_choice_mca_id"))] - { - routing_data.business_sub_label = first_connector_choice.sub_label; - } - return Ok(api::ConnectorCallType::Retryable(connector_data)); + return decide_connector_for_token_based_mit_flow( + payment_data, + routing_data, + connector_data, + ); } route_connector_v1( @@ -2804,13 +2799,107 @@ where merchant_account, business_profile, key_store, - &TransactionData::Payment(payment_data), + TransactionData::Payment(payment_data), routing_data, eligible_connectors, ) .await } +pub fn decide_connector_for_token_based_mit_flow<F: Clone>( + payment_data: &mut PaymentData<F>, + routing_data: &mut storage::RoutingData, + connectors: Vec<api::ConnectorData>, +) -> RouterResult<ConnectorCallType> { + if let Some((storage_enums::FutureUsage::OffSession, _)) = payment_data + .payment_intent + .setup_future_usage + .zip(payment_data.token_data.as_ref()) + { + logger::debug!("performing routing for token-based MIT flow"); + + let payment_method_info = payment_data + .payment_method_info + .as_ref() + .get_required_value("payment_method_info")?; + + let connector_mandate_details = payment_method_info + .connector_mandate_details + .clone() + .map(|details| { + details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize connector mandate details")? + .get_required_value("connector_mandate_details") + .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?; + + let mut connector_choice = None; + for connector_data in connectors { + if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { + if let Some(mandate_reference_record) = + connector_mandate_details.get(merchant_connector_id) + { + connector_choice = Some((connector_data, mandate_reference_record.clone())); + break; + } + } + } + + let (chosen_connector_data, mandate_reference_record) = connector_choice + .get_required_value("connector_choice") + .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("no eligible connector found for token-based MIT payment")?; + + routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = + chosen_connector_data.merchant_connector_id.clone(); + } + + payment_data.mandate_id = Some(payments_api::MandateIds { + mandate_id: None, + mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId( + payments_api::ConnectorMandateReferenceId { + connector_mandate_id: Some( + mandate_reference_record.connector_mandate_id.clone(), + ), + payment_method_id: Some(payment_method_info.payment_method_id.clone()), + update_history: None, + }, + )), + }); + + payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData { + payment_method_type: mandate_reference_record.payment_method_type, + original_payment_authorized_amount: mandate_reference_record + .original_payment_authorized_amount, + original_payment_authorized_currency: mandate_reference_record + .original_payment_authorized_currency, + }); + + Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) + } else { + let first_choice = connectors + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .into_report() + .attach_printable("no eligible connector found for payment")? + .clone(); + + routing_data.routed_through = Some(first_choice.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = first_choice.merchant_connector_id; + } + + Ok(api::ConnectorCallType::Retryable(connectors)) + } +} + pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool { let connector = payment_data.payment_attempt.connector.as_deref(); @@ -2940,7 +3029,7 @@ pub async fn route_connector_v1<F>( merchant_account: &domain::MerchantAccount, business_profile: &storage::business_profile::BusinessProfile, key_store: &domain::MerchantKeyStore, - transaction_data: &TransactionData<'_, F>, + transaction_data: TransactionData<'_, F>, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, ) -> RouterResult<ConnectorCallType> @@ -2948,7 +3037,7 @@ where F: Send + Clone, { #[allow(unused_variables)] - let (profile_id, routing_algorithm) = match transaction_data { + let (profile_id, routing_algorithm) = match &transaction_data { TransactionData::Payment(payment_data) => { if cfg!(feature = "business_profile_routing") { ( @@ -2983,7 +3072,7 @@ where state, &merchant_account.merchant_id, algorithm_ref, - transaction_data, + &transaction_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; @@ -2993,7 +3082,7 @@ where key_store, merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, - transaction_data, + &transaction_data, eligible_connectors, #[cfg(feature = "business_profile_routing")] profile_id, @@ -3002,6 +3091,7 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; + #[cfg(feature = "payouts")] let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) @@ -3009,17 +3099,6 @@ where .attach_printable("Empty connector list returned")? .clone(); - routing_data.routed_through = Some(first_connector_choice.connector.to_string()); - - #[cfg(feature = "connector_choice_mca_id")] - { - routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; - } - #[cfg(not(feature = "connector_choice_mca_id"))] - { - routing_data.business_sub_label = first_connector_choice.sub_label; - } - let connector_data = connectors .into_iter() .map(|conn| { @@ -3037,7 +3116,27 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - Ok(ConnectorCallType::Retryable(connector_data)) + match transaction_data { + TransactionData::Payment(payment_data) => { + decide_connector_for_token_based_mit_flow(payment_data, routing_data, connector_data) + } + + #[cfg(feature = "payouts")] + TransactionData::Payout(_) => { + routing_data.routed_through = Some(first_connector_choice.connector.to_string()); + + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; + } + #[cfg(not(feature = "connector_choice_mca_id"))] + { + routing_data.business_sub_label = first_connector_choice.sub_label; + } + + Ok(ConnectorCallType::Retryable(connector_data)) + } + } } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 212e694ac92..efc0e8852da 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -100,6 +100,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, + Some(resp.request.amount), + Some(resp.request.currency), )) .await?; @@ -134,6 +136,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, + Some(resp.request.amount), + Some(resp.request.currency), )) .await; diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 65342a1f06b..189a8a0a3ed 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -107,6 +107,8 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, + resp.request.amount, + Some(resp.request.currency), )) .await?; @@ -244,6 +246,8 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, + resp.request.amount, + Some(resp.request.currency), )) .await?; @@ -330,6 +334,8 @@ impl types::SetupMandateRouterData { merchant_account, self.request.payment_method_type, key_store, + resp.request.amount, + Some(resp.request.currency), )) .await? .0; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 76ffed499d1..68821ee5032 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1602,6 +1602,90 @@ pub async fn retrieve_card_with_permanent_token( Ok(api::PaymentMethodData::Card(api_card)) } +pub async fn retrieve_payment_method_from_db_with_token_data( + state: &AppState, + token_data: &storage::PaymentTokenData, +) -> RouterResult<Option<storage::PaymentMethod>> { + match token_data { + storage::PaymentTokenData::PermanentCard(data) => { + if let Some(ref payment_method_id) = data.payment_method_id { + state + .store + .find_payment_method(payment_method_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + .attach_printable("error retrieving payment method from DB") + .map(Some) + } else { + Ok(None) + } + } + + storage::PaymentTokenData::WalletToken(data) => state + .store + .find_payment_method(&data.payment_method_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + .attach_printable("error retrieveing payment method from DB") + .map(Some), + + storage::PaymentTokenData::Temporary(_) + | storage::PaymentTokenData::TemporaryGeneric(_) + | storage::PaymentTokenData::Permanent(_) + | storage::PaymentTokenData::AuthBankDebit(_) => Ok(None), + } +} + +pub async fn retrieve_payment_token_data( + state: &AppState, + token: String, + payment_method: Option<storage_enums::PaymentMethod>, +) -> RouterResult<storage::PaymentTokenData> { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let key = format!( + "pm_token_{}_{}_hyperswitch", + token, + payment_method.get_required_value("payment_method")? + ); + + let token_data_string = redis_conn + .get_key::<Option<String>>(&key) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch the token from redis")? + .ok_or(error_stack::Report::new( + errors::ApiErrorResponse::UnprocessableEntity { + message: "Token is invalid or expired".to_owned(), + }, + ))?; + + let token_data_result = token_data_string + .clone() + .parse_struct("PaymentTokenData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to deserialize hyperswitch token data"); + + let token_data = match token_data_result { + Ok(data) => data, + Err(e) => { + // The purpose of this logic is backwards compatibility to support tokens + // in redis that might be following the old format. + if token_data_string.starts_with('{') { + return Err(e); + } else { + storage::PaymentTokenData::temporary_generic(token_data_string) + } + } + }; + + Ok(token_data) +} + pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( operation: BoxedOperation<'a, F, R, Ctx>, state: &'a AppState, @@ -1630,72 +1714,13 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( } } - let token = payment_data.token.clone(); - - let hyperswitch_token = match payment_data.mandate_id { - Some(_) => token.map(storage::PaymentTokenData::temporary_generic), - None => { - if let Some(token) = token { - let redis_conn = state - .store - .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get redis connection")?; - - let key = format!( - "pm_token_{}_{}_hyperswitch", - token, - payment_data - .payment_attempt - .payment_method - .to_owned() - .get_required_value("payment_method")?, - ); - - let token_data_string = redis_conn - .get_key::<Option<String>>(&key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to fetch the token from redis")? - .ok_or(error_stack::Report::new( - errors::ApiErrorResponse::UnprocessableEntity { - message: "Token is invalid or expired".to_owned(), - }, - ))?; - - let token_data_result = token_data_string - .clone() - .parse_struct("PaymentTokenData") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to deserialize hyperswitch token data"); - - let token_data = match token_data_result { - Ok(data) => data, - Err(e) => { - // The purpose of this logic is backwards compatibility to support tokens - // in redis that might be following the old format. - if token_data_string.starts_with('{') { - return Err(e); - } else { - storage::PaymentTokenData::temporary_generic(token_data_string) - } - } - }; - - Some(token_data) - } else { - None - } - } - }; - // TODO: Handle case where payment method and token both are present in request properly. - let (payment_method, pm_id) = match (request, hyperswitch_token) { + let (payment_method, pm_id) = match (request, payment_data.token_data.as_ref()) { (_, Some(hyperswitch_token)) => { let pm_data = Ctx::retrieve_payment_method_with_token( state, merchant_key_store, - &hyperswitch_token, + hyperswitch_token, &payment_data.payment_intent, card_token_data.as_ref(), customer, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index ca6ed3e4ebd..6ad14d8fc4e 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -149,6 +149,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -158,6 +159,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 7d5bf73fc1f..2439646b3da 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -157,6 +157,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -166,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index d67151897aa..d643c86698d 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -202,6 +202,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -211,6 +212,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, refunds: vec![], disputes: vec![], attempts: 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 22ba50c07b9..79701db575b 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -131,6 +131,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> } } + let token_data = if let Some(token) = token.clone() { + Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?) + } else { + None + }; + payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; payment_attempt.payment_method_type = @@ -247,6 +253,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate, customer_acceptance: None, token, + token_data, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -259,6 +266,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .as_ref() .map(|pmd| pmd.payment_method_data.clone()), + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 2f548129a65..96de0cc924b 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -383,6 +383,23 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> &token, )?; + let (token_data, payment_method_info) = if let Some(token) = token.clone() { + let token_data = helpers::retrieve_payment_token_data( + state, + token, + payment_method.or(payment_attempt.payment_method), + ) + .await?; + + let payment_method_info = + helpers::retrieve_payment_method_from_db_with_token_data(state, &token_data) + .await?; + + (Some(token_data), payment_method_info) + } else { + (None, None) + }; + payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; payment_attempt.payment_method_type = @@ -548,6 +565,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate, customer_acceptance, token, + token_data, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -557,6 +575,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: request.confirm, payment_method_data: payment_method_data_after_card_bin_call, + payment_method_info, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b4ae0285dd1..bcc13ea1cef 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -302,7 +302,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_obj.connector_mandate_ids, ) { (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some( api_models::payments::MandateReferenceId::NetworkMandateId( network_tx_id, @@ -314,7 +314,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::MandateNotFound) .map(|connector_id: api_models::payments::ConnectorMandateReferenceId| { api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId{ connector_mandate_id: connector_id.connector_mandate_id, @@ -325,7 +325,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> } }), (_, _) => Ok(api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: None, }), } @@ -390,6 +390,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate, customer_acceptance, token, + token_data: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -399,6 +400,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: request.confirm, payment_method_data: payment_method_data_after_card_bin_call, + payment_method_info: None, refunds: vec![], disputes: vec![], attempts: None, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 66bab03d047..36197a9463b 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -154,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 18e568eb9b8..eaded6b5e65 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -654,7 +654,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( mandate_id: payment_data .mandate_id .clone() - .map(|mandate| mandate.mandate_id), + .and_then(|mandate| mandate.mandate_id), connector_metadata, payment_token: None, error_code: error_status.clone(), @@ -844,7 +844,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .or(payment_data .mandate_id .clone() - .map(|mandate_ids| mandate_ids.mandate_id)); + .and_then(|mandate_ids| mandate_ids.mandate_id)); let m_router_data_response = router_data.response.clone(); let mandate_update_fut = tokio::spawn( async move { diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index e64b41ed383..d498e1baca4 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -169,6 +169,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_connector: None, customer_acceptance: None, token: None, + token_data: None, setup_mandate: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), @@ -179,6 +180,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 885d2593ba8..f1264868ff7 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -114,6 +114,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ) .await?; + let token_data = if let Some(token) = payment_attempt.payment_token.clone() { + Some( + helpers::retrieve_payment_token_data(state, token, payment_attempt.payment_method) + .await?, + ) + } else { + None + }; + 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); @@ -147,6 +156,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: payment_attempt.payment_token.clone(), + token_data, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -157,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> confirm: Some(payment_attempt.confirm), payment_attempt, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index f36a2eea81d..66f0527c35d 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -410,13 +410,14 @@ async fn get_tracker_for_sync< .mandate_id .clone() .map(|id| api_models::payments::MandateIds { - mandate_id: id, + mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), @@ -426,6 +427,7 @@ async fn get_tracker_for_sync< }, confirm: Some(request.force_sync), payment_method_data: None, + payment_method_info: None, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(&payment_attempt.status) diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c5fda22ed87..0ce77dfcd13 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -254,6 +254,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> )?; } + let token_data = if let Some(token) = token.clone() { + Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?) + } else { + None + }; + let mandate_id = request .mandate_id .as_ref() @@ -268,7 +274,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_obj.connector_mandate_ids, ) { (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some( api_models::payments::MandateReferenceId::NetworkMandateId( network_tx_id, @@ -280,14 +286,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::MandateNotFound) .map(|connector_id: api_models::payments::ConnectorMandateReferenceId| { api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None }, )) } }), (_, _) => Ok(api_models::payments::MandateIds { - mandate_id: mandate_obj.mandate_id, + mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: None, }), } @@ -383,6 +389,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id, mandate_connector, token, + token_data, setup_mandate, customer_acceptance, address: PaymentAddress { @@ -395,6 +402,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .as_ref() .map(|pmd| pmd.payment_method_data.clone()), + payment_method_info: None, force_sync: None, refunds: vec![], disputes: 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 dbdf1c062ac..0157822cdf8 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -122,6 +122,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> setup_mandate: None, customer_acceptance: None, token: None, + token_data: None, address: PaymentAddress { billing: None, shipping: None, @@ -129,6 +130,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> }, confirm: None, payment_method_data: None, + payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 91b6061c111..2af73f29909 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -377,7 +377,7 @@ where mandate_id: payment_data .mandate_id .clone() - .map(|mandate| mandate.mandate_id), + .and_then(|mandate| mandate.mandate_id), connector_metadata, payment_token: None, error_code: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 7aaaaed92aa..4628f027a05 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -39,6 +39,8 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, + amount: Option<i64>, + currency: Option<storage_enums::Currency>, ) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)> where FData: mandate::MandateBehaviour, @@ -94,7 +96,13 @@ where .map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession) .unwrap_or(false) { - add_connector_mandate_details_in_payment_method(responses, connector) + add_connector_mandate_details_in_payment_method( + responses, + payment_method_type, + amount, + currency, + connector, + ) } else { None } @@ -648,6 +656,9 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( fn add_connector_mandate_details_in_payment_method( resp: types::PaymentsResponseData, + payment_method_type: Option<storage_enums::PaymentMethodType>, + authorized_amount: Option<i64>, + authorized_currency: Option<storage_enums::Currency>, connector: &api::ConnectorData, ) -> Option<storage::PaymentsMandateReference> { let mut mandate_details = HashMap::new(); @@ -665,8 +676,20 @@ fn add_connector_mandate_details_in_payment_method( _ => None, }; - if let Some(mca_id) = connector.merchant_connector_id.clone() { - mandate_details.insert(mca_id, connector_mandate_id); + if let Some((mca_id, connector_mandate_id)) = connector + .merchant_connector_id + .clone() + .zip(connector_mandate_id) + { + mandate_details.insert( + mca_id, + storage::PaymentsMandateReferenceRecord { + connector_mandate_id, + payment_method_type, + original_payment_authorized_amount: authorized_amount, + original_payment_authorized_currency: authorized_currency, + }, + ); Some(storage::PaymentsMandateReference(mandate_details)) } else { None diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8e5b2c9199e..0ae04aaddce 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -327,7 +327,9 @@ where phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), - mandate_id: data.mandate_id.map(|mandate_ids| mandate_ids.mandate_id), + mandate_id: data + .mandate_id + .and_then(|mandate_ids| mandate_ids.mandate_id), payment_method: data.payment_attempt.payment_method, payment_method_data: payment_method_data_response, payment_token: data.token, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 9fd7458155a..847c555a86d 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -600,7 +600,7 @@ pub async fn decide_payout_connector( merchant_account, &payout_data.business_profile, key_store, - &TransactionData::<()>::Payout(payout_data), + TransactionData::<()>::Payout(payout_data), routing_data, eligible_connectors, ) diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 31a2e05dd79..0d9c7f4f62c 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -36,12 +36,11 @@ use crate::{core::errors, services::api as service_api, types::storage}; #[cfg(feature = "business_profile_routing")] use crate::{errors, services::api as service_api}; -#[derive(Clone)] pub enum TransactionData<'a, F> where F: Clone, { - Payment(&'a payments::PaymentData<F>), + Payment(&'a mut payments::PaymentData<F>), #[cfg(feature = "payouts")] Payout(&'a payouts::PayoutData), } diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 8edfb8b36d8..d3339b7c4be 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -1,4 +1,7 @@ -use std::collections::HashMap; +use std::{ + collections::HashMap, + ops::{Deref, DerefMut}, +}; use api_models::payment_methods; use diesel_models::enums; @@ -40,7 +43,7 @@ pub struct WalletTokenData { pub payment_method_id: String, } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PaymentTokenData { // The variants 'Temporary' and 'Permanent' are added for backwards compatibility @@ -76,4 +79,26 @@ impl PaymentTokenData { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct PaymentsMandateReference(pub HashMap<String, Option<String>>); +pub struct PaymentsMandateReferenceRecord { + pub connector_mandate_id: String, + pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub original_payment_authorized_amount: Option<i64>, + pub original_payment_authorized_currency: Option<common_enums::Currency>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentsMandateReference(pub HashMap<String, PaymentsMandateReferenceRecord>); + +impl Deref for PaymentsMandateReference { + type Target = HashMap<String, PaymentsMandateReferenceRecord>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for PaymentsMandateReference { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +}
2024-03-07T12:39:39Z
## Description <!-- Describe your changes in detail --> This PR adds routing support for token-based MIT payments. Basically, the merchant can have their customers set up their payment method for off session payments with Hyperswitch. Behind the scenes, Hyperswitch sets up an MIT/Mandate with the connector. Now, when the merchant wants to do off-session payments using the customer's saved payment method by using a token to select the payment method, the backend needs to ensure that the payment goes through only those connectors for which that payment method is set up for MITs. This PR adds this check. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The merchant may want to do off-session payments by passing a payment method token on behalf of their customers. This would require the smart router to choose an appropriate connector for the payment on the basis of whether the selected payment method is set up with the connector for off-session MIT payments. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a Merchant Account, and a Merchant Connector Account (preferably Cybersource) 2. Create and Confirm a `Setup Mandate` request ```bash curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_OnB9g3l1v3cqPalObMlJ874jZerIsl9hlNCoTdXzNyiB2K7Edrp3wEQYmdmnXFJM' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "profile_id": "pro_9ci3SqA4bSAe7g3C7jCp", "capture_method": "automatic", "customer_id": "MyCustomer123456", "email": "guest@example.com", "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "payment_type": "setup_mandate", "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" }' ``` this will set the given card up for token-based MIT payments, and associate the connector MIT/Mandate details with the saved payment method in DB as shown below in the `connector_mandate_details` column <img width="1727" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/4c8aefe5-3079-43df-ac13-3226a291f006"> 3. Next, to make a token-based MIT payment, Create a payment with `setup_future_usage = off_session` ```bash curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": false, "profile_id": "pro_tsOrBWXnZfzYRJ9Jm7Dk", "capture_method": "automatic", "customer_id": "MyCustomer123456", "email": "guest@example.com", "setup_future_usage": "off_session", "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" }' ``` 4. Do a list customer payment methods call and confirm the payment with the token (no need to pass `card_cvc`) ```bash curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data '{ "payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ", "payment_method": "card" }' ``` This is treated as a token-based MIT payment since we passed `setup_future_usage = off_session` in create, and are confirming the payment with the token. Routing will detect this, get the `connector_mandate_details` from the payment method object associated with the token, and do a recurring mandate payment using the connector mandate details. Additionally, routing will ensure that the connector will be picked for a token-based MIT payment if and only if it has some connector mandate details saved in the payment method object. Following is the connector request sent by the backend to cybersource. ```json {"processingInformation":{"actionList":null,"actionTokenTypes":null,"authorizationOptions":{"initiator":null,"merchantIntitiatedTransaction":{"reason":null,"originalAuthorizedAmount":"0.00"}},"commerceIndicator":"internet","capture":true,"captureOptions":null,"paymentSolution":null},"paymentInformation":{"paymentInstrument":{"id":"1323EB5C00917EC2E063A2598D0A69D7"}},"orderInformation":{"amountDetails":{"totalAmount":"2.00","currency":"USD"},"billTo":{"firstName":"One","lastName":"Two","address1":"here","locality":"bengaluru","administrativeArea":"Karnataka","postalCode":"560095","country":"IN","email":"guest@example.com"}},"clientReferenceInformation":{"code":"pay_iCiIdD8UqO3SdfAxGRrI_1"}} ``` We can see that `paymentInstrument` was set to the connector mandate ID by Routing, thus turning it into a recurring MIT payment. 5. To test and ensure that Routing picks a connector for token-based MIT payments if and only if it has connector_mandate_details for that connector, create another merchant connector account with a different connector `Y`. 6. Repeat steps 3 and 4 but in the confirm call, pass a `"routing"` value to force straight through routing to pick `Y`. ```bash curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data '{ "payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ", "routing": { "type": "single", "data": { "connector": "stripe", "merchant_connector_id": "mca_hji9rSpSJPUOYn2A9yL9" } }, "payment_method": "card" }' ``` Even tho we are forcing connector `Y` for the token-based MIT payment, Routing will detect that the chosen payment method does not have any MIT/Mandate set up with `Y` by checking the `connector_mandate_details` field in the payment method record, and automatically fall back to the first connector. <img width="552" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/5eb49d36-0c6b-43d6-8bae-9f9bf45bcd31">
7391416e2473eab0474bd01bb155a9ecc96da263
1. Create a Merchant Account, and a Merchant Connector Account (preferably Cybersource) 2. Create and Confirm a `Setup Mandate` request ```bash curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_OnB9g3l1v3cqPalObMlJ874jZerIsl9hlNCoTdXzNyiB2K7Edrp3wEQYmdmnXFJM' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "profile_id": "pro_9ci3SqA4bSAe7g3C7jCp", "capture_method": "automatic", "customer_id": "MyCustomer123456", "email": "guest@example.com", "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "payment_type": "setup_mandate", "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" }' ``` this will set the given card up for token-based MIT payments, and associate the connector MIT/Mandate details with the saved payment method in DB as shown below in the `connector_mandate_details` column <img width="1727" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/4c8aefe5-3079-43df-ac13-3226a291f006"> 3. Next, to make a token-based MIT payment, Create a payment with `setup_future_usage = off_session` ```bash curl --location 'http://127.0.0.1:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": false, "profile_id": "pro_tsOrBWXnZfzYRJ9Jm7Dk", "capture_method": "automatic", "customer_id": "MyCustomer123456", "email": "guest@example.com", "setup_future_usage": "off_session", "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" }' ``` 4. Do a list customer payment methods call and confirm the payment with the token (no need to pass `card_cvc`) ```bash curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data '{ "payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ", "payment_method": "card" }' ``` This is treated as a token-based MIT payment since we passed `setup_future_usage = off_session` in create, and are confirming the payment with the token. Routing will detect this, get the `connector_mandate_details` from the payment method object associated with the token, and do a recurring mandate payment using the connector mandate details. Additionally, routing will ensure that the connector will be picked for a token-based MIT payment if and only if it has some connector mandate details saved in the payment method object. Following is the connector request sent by the backend to cybersource. ```json {"processingInformation":{"actionList":null,"actionTokenTypes":null,"authorizationOptions":{"initiator":null,"merchantIntitiatedTransaction":{"reason":null,"originalAuthorizedAmount":"0.00"}},"commerceIndicator":"internet","capture":true,"captureOptions":null,"paymentSolution":null},"paymentInformation":{"paymentInstrument":{"id":"1323EB5C00917EC2E063A2598D0A69D7"}},"orderInformation":{"amountDetails":{"totalAmount":"2.00","currency":"USD"},"billTo":{"firstName":"One","lastName":"Two","address1":"here","locality":"bengaluru","administrativeArea":"Karnataka","postalCode":"560095","country":"IN","email":"guest@example.com"}},"clientReferenceInformation":{"code":"pay_iCiIdD8UqO3SdfAxGRrI_1"}} ``` We can see that `paymentInstrument` was set to the connector mandate ID by Routing, thus turning it into a recurring MIT payment. 5. To test and ensure that Routing picks a connector for token-based MIT payments if and only if it has connector_mandate_details for that connector, create another merchant connector account with a different connector `Y`. 6. Repeat steps 3 and 4 but in the confirm call, pass a `"routing"` value to force straight through routing to pick `Y`. ```bash curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \ --data '{ "payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ", "routing": { "type": "single", "data": { "connector": "stripe", "merchant_connector_id": "mca_hji9rSpSJPUOYn2A9yL9" } }, "payment_method": "card" }' ``` Even tho we are forcing connector `Y` for the token-based MIT payment, Routing will detect that the chosen payment method does not have any MIT/Mandate set up with `Y` by checking the `connector_mandate_details` field in the payment method record, and automatically fall back to the first connector. <img width="552" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/5eb49d36-0c6b-43d6-8bae-9f9bf45bcd31">
[ "config/development.toml", "crates/api_models/src/payments.rs", "crates/router/src/connector/dlocal/transformers.rs", "crates/router/src/core/mandate.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/flows/authorize_flow.rs", "crates/router/src/core/payments/flows/setup_mandate...
juspay/hyperswitch
juspay__hyperswitch-3914
Bug: [FEATURE] statement_descriptor_suffix and statement_descriptor_name not being sent to Adyen. Please implement. ### Feature Description It is important to be able to have custom statements (and also it is available feature on Stripe), so it should be on Adyen as well. ### Possible Implementation It should propagate to `shopperStatement` in the Adyen't API ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 382ad018f1d..7c543feed7e 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -17,7 +17,7 @@ payout_connector_list = "wise" [connectors] aci.base_url = "https://eu-test.oppwa.com/" -adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/" +adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout" adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" diff --git a/config/development.toml b/config/development.toml index 6d4914af8b4..41497021c3a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -88,7 +88,7 @@ vault_private_key = "" tunnel_private_key = "" [connectors.supported] -wallets = ["klarna", "braintree", "applepay"] +wallets = ["klarna", "braintree", "applepay", "adyen"] rewards = ["cashtocode", "zen"] cards = [ "aci", @@ -323,8 +323,8 @@ pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} -ideal = { country = "NL", currency = "EUR" } +sofort = {not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +ideal = { not_available_flows = { capture_method = "manual" }, country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"} diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index c44d590e2f1..8af99420fa4 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -9,12 +9,10 @@ use reqwest::Url; use serde::{Deserialize, Serialize}; use time::{Duration, OffsetDateTime, PrimitiveDateTime}; -#[cfg(feature = "payouts")] -use crate::{connector::utils::AddressDetailsData, types::api::payouts, utils::OptionExt}; use crate::{ connector::utils::{ - self, BrowserInformationData, CardData, MandateReferenceData, PaymentsAuthorizeRequestData, - RouterData, + self, AddressDetailsData, BrowserInformationData, CardData, MandateReferenceData, + PaymentsAuthorizeRequestData, RouterData, }, consts, core::errors, @@ -29,6 +27,8 @@ use crate::{ }, utils as crate_utils, }; +#[cfg(feature = "payouts")] +use crate::{types::api::payouts, utils::OptionExt}; type Error = error_stack::Report<errors::ConnectorError>; @@ -130,12 +130,12 @@ pub struct ShopperName { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Address { - city: Option<String>, - country: Option<api_enums::CountryAlpha2>, - house_number_or_name: Option<Secret<String>>, - postal_code: Option<Secret<String>>, + city: String, + country: api_enums::CountryAlpha2, + house_number_or_name: Secret<String>, + postal_code: Secret<String>, state_or_province: Option<Secret<String>>, - street: Option<Secret<String>>, + street: Secret<String>, } #[derive(Debug, Serialize)] @@ -165,8 +165,11 @@ pub struct AdyenPaymentRequest<'a> { shopper_reference: Option<String>, store_payment_method: Option<bool>, shopper_name: Option<ShopperName>, + #[serde(rename = "shopperIP")] + shopper_ip: Option<Secret<String, pii::IpAddress>>, shopper_locale: Option<String>, shopper_email: Option<Email>, + shopper_statement: Option<String>, social_security_number: Option<Secret<String>>, telephone_number: Option<Secret<String>>, billing_address: Option<Address>, @@ -174,6 +177,7 @@ pub struct AdyenPaymentRequest<'a> { country_code: Option<api_enums::CountryAlpha2>, line_items: Option<Vec<LineItem>>, channel: Option<Channel>, + metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Serialize)] @@ -1729,16 +1733,22 @@ fn get_amount_data(item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>) } } -fn get_address_info(address: Option<&api_models::payments::Address>) -> Option<Address> { +fn get_address_info( + address: Option<&api_models::payments::Address>, +) -> Option<Result<Address, error_stack::Report<errors::ConnectorError>>> { address.and_then(|add| { - add.address.as_ref().map(|a| Address { - city: a.city.clone(), - country: a.country, - house_number_or_name: a.line1.clone(), - postal_code: a.zip.clone(), - state_or_province: a.state.clone(), - street: a.line2.clone(), - }) + add.address.as_ref().map( + |a| -> Result<Address, error_stack::Report<errors::ConnectorError>> { + Ok(Address { + city: a.get_city()?.to_owned(), + country: a.get_country()?.to_owned(), + house_number_or_name: a.get_line1()?.to_owned(), + postal_code: a.get_zip()?.to_owned(), + state_or_province: a.state.clone(), + street: a.get_line2()?.to_owned(), + }) + }, + ) }) } @@ -1823,6 +1833,12 @@ fn get_social_security_number( } } +fn build_shopper_reference(customer_id: &Option<String>, merchant_id: String) -> Option<String> { + customer_id + .clone() + .map(|c_id| format!("{}_{}", merchant_id, c_id)) +} + impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a> { type Error = Error; fn try_from( @@ -2125,27 +2141,81 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { } } -impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)> - for AdyenPaymentMethod<'a> +pub fn check_required_field<'a, T>( + field: &'a Option<T>, + message: &'static str, +) -> Result<&'a T, errors::ConnectorError> { + field + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: message, + }) +} + +impl<'a> + TryFrom<( + &api::PayLaterData, + &Option<api_enums::CountryAlpha2>, + &Option<Email>, + &Option<String>, + &Option<ShopperName>, + &Option<Secret<String>>, + &Option<Address>, + &Option<Address>, + )> for AdyenPaymentMethod<'a> { type Error = Error; fn try_from( - value: (&api::PayLaterData, Option<api_enums::CountryAlpha2>), + value: ( + &api::PayLaterData, + &Option<api_enums::CountryAlpha2>, + &Option<Email>, + &Option<String>, + &Option<ShopperName>, + &Option<Secret<String>>, + &Option<Address>, + &Option<Address>, + ), ) -> Result<Self, Self::Error> { - let (pay_later_data, country_code) = value; + let ( + pay_later_data, + country_code, + shopper_email, + shopper_reference, + shopper_name, + telephone_number, + billing_address, + delivery_address, + ) = value; match pay_later_data { api_models::payments::PayLaterData::KlarnaRedirect { .. } => { let klarna = PmdForPaymentType { payment_type: PaymentType::Klarna, }; + check_required_field(shopper_email, "email")?; + check_required_field(shopper_reference, "customer_id")?; + check_required_field(country_code, "billing.country")?; + Ok(AdyenPaymentMethod::AdyenKlarna(Box::new(klarna))) } - api_models::payments::PayLaterData::AffirmRedirect { .. } => Ok( - AdyenPaymentMethod::AdyenAffirm(Box::new(PmdForPaymentType { - payment_type: PaymentType::Affirm, - })), - ), + api_models::payments::PayLaterData::AffirmRedirect { .. } => { + check_required_field(shopper_email, "email")?; + check_required_field(shopper_name, "billing.first_name, billing.last_name")?; + check_required_field(telephone_number, "billing.phone")?; + check_required_field(billing_address, "billing")?; + + Ok(AdyenPaymentMethod::AdyenAffirm(Box::new( + PmdForPaymentType { + payment_type: PaymentType::Affirm, + }, + ))) + } api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { + check_required_field(shopper_email, "email")?; + check_required_field(shopper_name, "billing.first_name, billing.last_name")?; + check_required_field(delivery_address, "shipping")?; + check_required_field(billing_address, "billing")?; + if let Some(country) = country_code { match country { api_enums::CountryAlpha2::IT @@ -2163,17 +2233,36 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)> } } api_models::payments::PayLaterData::PayBrightRedirect { .. } => { + check_required_field(shopper_name, "billing.first_name, billing.last_name")?; + check_required_field(telephone_number, "billing.phone")?; + check_required_field(shopper_email, "email")?; + check_required_field(billing_address, "billing")?; + check_required_field(delivery_address, "shipping")?; + check_required_field(country_code, "billing.country")?; Ok(AdyenPaymentMethod::PayBright) } api_models::payments::PayLaterData::WalleyRedirect { .. } => { + //[TODO: Line items specific sub-fields are mandatory] + check_required_field(telephone_number, "billing.phone")?; + check_required_field(shopper_email, "email")?; Ok(AdyenPaymentMethod::Walley) } - api_models::payments::PayLaterData::AlmaRedirect { .. } => Ok( - AdyenPaymentMethod::AlmaPayLater(Box::new(PmdForPaymentType { - payment_type: PaymentType::Alma, - })), - ), + api_models::payments::PayLaterData::AlmaRedirect { .. } => { + check_required_field(telephone_number, "billing.phone")?; + check_required_field(shopper_email, "email")?; + check_required_field(billing_address, "billing")?; + check_required_field(delivery_address, "shipping")?; + Ok(AdyenPaymentMethod::AlmaPayLater(Box::new( + PmdForPaymentType { + payment_type: PaymentType::Alma, + }, + ))) + } api_models::payments::PayLaterData::AtomeRedirect { .. } => { + check_required_field(shopper_email, "email")?; + check_required_field(shopper_name, "billing.first_name, billing.last_name")?; + check_required_field(telephone_number, "billing.phone")?; + check_required_field(billing_address, "billing")?; Ok(AdyenPaymentMethod::Atome) } payments::PayLaterData::KlarnaSdk { .. } => Err(errors::ConnectorError::NotSupported { @@ -2544,6 +2633,9 @@ impl<'a> shopper_reference, store_payment_method, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -2564,12 +2656,22 @@ impl<'a> let amount = get_amount_data(item); let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?; let shopper_interaction = AdyenShopperInteraction::from(item.router_data); - let (recurring_processing_model, store_payment_method, shopper_reference) = + let shopper_reference = build_shopper_reference( + &item.router_data.customer_id, + item.router_data.merchant_id.clone(), + ); + let (recurring_processing_model, store_payment_method, _) = get_recurring_processing_model(item.router_data)?; let browser_info = get_browser_info(item.router_data)?; + let billing_address = + get_address_info(item.router_data.address.billing.as_ref()).transpose()?; + let country_code = get_country_code(item.router_data.address.billing.as_ref()); let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(card_data)?; + let shopper_email = item.router_data.request.email.clone(); + let shopper_name = get_shopper_name(item.router_data.address.billing.as_ref()); + Ok(AdyenPaymentRequest { amount, merchant_account: auth_type.merchant_account, @@ -2581,17 +2683,20 @@ impl<'a> browser_info, additional_data, telephone_number: None, - shopper_name: None, - shopper_email: None, + shopper_name, + shopper_email, shopper_locale: None, social_security_number: None, - billing_address: None, + billing_address, delivery_address: None, - country_code: None, + country_code, line_items: None, shopper_reference, store_payment_method, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -2642,6 +2747,9 @@ impl<'a> shopper_reference: None, store_payment_method: None, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -2693,6 +2801,9 @@ impl<'a> shopper_reference: None, store_payment_method: None, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -2740,6 +2851,9 @@ impl<'a> shopper_reference: None, store_payment_method: None, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -2787,6 +2901,9 @@ impl<'a> store_payment_method: None, channel: None, social_security_number: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -2841,6 +2958,9 @@ impl<'a> shopper_reference, store_payment_method, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -2935,6 +3055,9 @@ impl<'a> shopper_reference, store_payment_method, channel, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -2958,18 +3081,33 @@ impl<'a> let browser_info = get_browser_info(item.router_data)?; let additional_data = get_additional_data(item.router_data); let country_code = get_country_code(item.router_data.address.billing.as_ref()); - let payment_method = AdyenPaymentMethod::try_from((paylater_data, country_code))?; let shopper_interaction = AdyenShopperInteraction::from(item.router_data); - let (recurring_processing_model, store_payment_method, shopper_reference) = + let shopper_reference = build_shopper_reference( + &item.router_data.customer_id, + item.router_data.merchant_id.clone(), + ); + let (recurring_processing_model, store_payment_method, _) = get_recurring_processing_model(item.router_data)?; let return_url = item.router_data.request.get_return_url()?; let shopper_name: Option<ShopperName> = get_shopper_name(item.router_data.address.billing.as_ref()); let shopper_email = item.router_data.request.email.clone(); - let billing_address = get_address_info(item.router_data.address.billing.as_ref()); - let delivery_address = get_address_info(item.router_data.address.shipping.as_ref()); + let billing_address = + get_address_info(item.router_data.address.billing.as_ref()).transpose()?; + let delivery_address = + get_address_info(item.router_data.address.shipping.as_ref()).transpose()?; let line_items = Some(get_line_items(item)); let telephone_number = get_telephone_number(item.router_data); + let payment_method = AdyenPaymentMethod::try_from(( + paylater_data, + &country_code, + &shopper_email, + &shopper_reference, + &shopper_name, + &telephone_number, + &billing_address, + &delivery_address, + ))?; Ok(AdyenPaymentRequest { amount, merchant_account: auth_type.merchant_account, @@ -2992,6 +3130,9 @@ impl<'a> shopper_reference, store_payment_method, channel: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3047,6 +3188,9 @@ impl<'a> store_payment_method: None, channel: None, social_security_number: None, + shopper_statement: item.router_data.request.statement_descriptor.clone(), + shopper_ip: item.router_data.request.get_ip_address_as_optional(), + metadata: item.router_data.request.metadata.clone(), }) } } @@ -4522,7 +4666,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC date_of_birth: None, entity_type: Some(item.router_data.request.entity_type), nationality: get_country_code(item.router_data.address.billing.as_ref()), - billing_address: get_address_info(item.router_data.address.billing.as_ref()), + billing_address: get_address_info(item.router_data.address.billing.as_ref()) + .transpose()?, }) } PayoutMethodData::Wallet(wallet_data) => { @@ -4561,7 +4706,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC date_of_birth: None, entity_type: Some(item.router_data.request.entity_type), nationality: get_country_code(item.router_data.address.billing.as_ref()), - billing_address: get_address_info(item.router_data.address.billing.as_ref()), + billing_address: get_address_info(item.router_data.address.billing.as_ref()) + .transpose()?, }) } } @@ -4598,7 +4744,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutF currency: item.router_data.request.destination_currency, }, card: PayoutCardDetails::try_from(&item.router_data.get_payout_method_data()?)?, - billing_address: get_address_info(item.router_data.get_billing().ok()), + billing_address: get_address_info(item.router_data.get_billing().ok()) + .transpose()?, merchant_account, reference: item.router_data.request.payout_id.clone(), shopper_name: ShopperName {
2024-03-07T12:25:27Z
## Description <!-- Describe your changes in detail --> - Add shopper statement and metadata in payments request - Add additional fields and validations over fields like `IP address`, `billing_address`, `Email` and Shopper details ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [X] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> Production URL got updated for Adyen ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3914 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create Klarna Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_B0AWG00VLGTFt4rTrj6a", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Test in Adyen dashboard all the fields should be visible like shopper statement, address and shopper reference - Klarna Validation when not sending Email ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_B0AWG00VLGTFt4rTrj6a", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Expected Response: ``` { "error": { "type": "invalid_request", "message": "Missing required param: email", "code": "IR_04" } } ```
7391416e2473eab0474bd01bb155a9ecc96da263
- Create Klarna Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_B0AWG00VLGTFt4rTrj6a", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Test in Adyen dashboard all the fields should be visible like shopper statement, address and shopper reference - Klarna Validation when not sending Email ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_B0AWG00VLGTFt4rTrj6a", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Expected Response: ``` { "error": { "type": "invalid_request", "message": "Missing required param: email", "code": "IR_04" } } ```
[ "config/deployments/production.toml", "config/development.toml", "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4009
Bug: [BUG] Fix failing postman collections ### Feature Description Fix failing postman collections for cybersource, checkout and bluesnap ### Possible Implementation Add customer_acceptance for all the save card flows ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json index 16f6e13983f..3ba8c394b4c 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json @@ -38,19 +38,21 @@ } }, "raw_json_formatted": { - "client_secret": "{{client_secret}}" + "client_secret": "{{client_secret}}", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + } } }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json index 878ea581a93..8bd119ed2fe 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json index 5e3ff0e70ad..8ea0f5f2039 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json index 6694ff2b22a..aa9635024c5 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json index 9260edb1a99..2b6e0287d48 100644 --- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json index d69394e2926..188c0b38676 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -88,12 +96,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json index 5332a1326c1..f40ab119265 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -88,12 +96,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json index ad06c8ad4bd..dbc19ce0181 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json @@ -82,14 +82,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json index e7fc25844ab..48692ab2b3e 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json @@ -29,6 +29,14 @@ "customer_id": "{{customer_id}}", "email": "guest@example.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", @@ -82,12 +90,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json index 0fc9b71ff57..261af340978 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", @@ -95,12 +103,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json index c564a62c80e..6e5824386eb 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json @@ -66,6 +66,14 @@ } } }, + "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" + } + }, "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", @@ -82,14 +90,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json index fd771e557f8..9fd1a203309 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json @@ -51,6 +51,14 @@ } }, "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" + } + }, "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", @@ -67,14 +75,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json index 063c7b86048..93441083df2 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json @@ -29,6 +29,14 @@ "customer_id": "{{customer_id}}", "email": "guest@example.com", "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" + } + }, "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", @@ -82,12 +90,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json index f0be44bec91..5815567de25 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", @@ -95,12 +103,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json index 5f55f09c9b4..7cb43e8b741 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json @@ -32,6 +32,14 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "setup_future_usage": "off_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" + } + }, "return_url": "https://duck.com", "billing": { "address": { @@ -69,12 +77,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 4bf62f4f29f..fd997c7b6ba 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -95,12 +103,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json index a735ee48661..f9d3875c121 100644 --- a/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 52be363a049..36b559bcf62 100644 --- a/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 57d625e7c39..600979ea851 100644 --- a/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index ed87e6ed332..b32011d26dc 100644 --- a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index d5cb30f4c1b..3db3bf69950 100644 --- a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index ed87e6ed332..b32011d26dc 100644 --- a/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json index 20007308fe7..c7c7d114f5f 100644 --- a/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json index 20007308fe7..c7c7d114f5f 100644 --- a/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json +++ b/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 011e150c4ec..10a0feda0a3 100644 --- a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 8e9afa774b3..c3143943700 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index 9c932aa537d..d7511caf779 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json index 9d317ce5293..5c8e5db8976 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json @@ -22,9 +22,7 @@ "currency": "USD", "confirm": true, "capture_method": "automatic", - "connector": [ - "nuvei" - ], + "connector": ["nuvei"], "customer_id": "futurebilling", "email": "guest@example.com", "name": "John Doe", @@ -65,6 +63,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -100,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json index 93f6d30da08..b3d0168f52d 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json @@ -22,9 +22,7 @@ "currency": "USD", "confirm": true, "capture_method": "automatic", - "connector": [ - "nuvei" - ], + "connector": ["nuvei"], "customer_id": "futurebilling", "email": "guest@example.com", "name": "John Doe", @@ -65,6 +63,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -100,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json index b9cbf1fa7a5..b1cdc93dac8 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json @@ -22,9 +22,7 @@ "currency": "USD", "confirm": true, "capture_method": "automatic", - "connector": [ - "nuvei" - ], + "connector": ["nuvei"], "customer_id": "futurebilling", "email": "guest@example.com", "name": "John Doe", @@ -65,6 +63,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -100,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json index 41edc08e2f9..10a6b680c8c 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json @@ -22,9 +22,7 @@ "currency": "USD", "confirm": true, "capture_method": "automatic", - "connector": [ - "nuvei" - ], + "connector": ["nuvei"], "customer_id": "futurebilling", "email": "guest@example.com", "name": "John Doe", @@ -65,6 +63,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -100,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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" }
2024-03-07T12:22:35Z
## Description fix postman collections for saving cards with customer_acceptance ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <img width="1296" alt="Screenshot 2024-03-07 at 6 09 36 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/a2d7f54b-e6b7-403e-982b-41a572ed70be">
f9b6f5da36c3a57da4b89db3151996403e2f3dfd
<img width="1296" alt="Screenshot 2024-03-07 at 6 09 36 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/a2d7f54b-e6b7-403e-982b-41a572ed70be">
[ "postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json", "postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json", "postman/collection-dir/ba...
juspay/hyperswitch
juspay__hyperswitch-3998
Bug: Creating a domain config (ENV) - `nrid_supported_connectors` Create a application level config (`nrid_supported_connectors`) that contains the list of connectors that supports pg agnostic MITs,
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 77040f79a4a..67dfddd0d55 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -129,6 +129,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay" card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8ae12dc54a6..03dc7825222 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -128,6 +128,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay" card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/development.toml b/config/development.toml index 8ba5c076071..5cdd5f0b9bf 100644 --- a/config/development.toml +++ b/config/development.toml @@ -511,6 +511,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" } card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index eb32b47e3b4..1077bf34c02 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -381,6 +381,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" } card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [connector_customer] connector_list = "gocardless,stax,stripe" payout_connector_list = "wise" diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index ef153c23a7b..681a57bda87 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -38,6 +38,7 @@ pub struct PaymentMethod { pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, + pub network_transaction_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)] @@ -69,6 +70,7 @@ pub struct PaymentMethodNew { pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, + pub network_transaction_id: Option<String>, } impl Default for PaymentMethodNew { @@ -102,6 +104,7 @@ impl Default for PaymentMethodNew { connector_mandate_details: Option::default(), customer_acceptance: Option::default(), status: storage_enums::PaymentMethodStatus::Active, + network_transaction_id: Option::default(), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 8e8bf48a538..ad30609a770 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -913,6 +913,8 @@ diesel::table! { customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, + #[max_length = 255] + network_transaction_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 6906b5a3e7a..537f6666c5d 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -335,6 +335,8 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "email")] email: conf.email, mandates: conf.mandates, + network_transaction_id_supported_connectors: conf + .network_transaction_id_supported_connectors, required_fields: conf.required_fields, delayed_session_response: conf.delayed_session_response, webhook_source_verification_call: conf.webhook_source_verification_call, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index d92812cee40..a0dce991295 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -91,6 +91,7 @@ pub struct Settings<S: SecretState> { pub email: EmailSettings, pub cors: CorsSettings, pub mandates: Mandates, + pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, @@ -251,6 +252,12 @@ pub struct Mandates { pub update_mandate_supported: SupportedPaymentMethodsForMandate, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct NetworkTransactionIdSupportedConnectors { + #[serde(deserialize_with = "deserialize_hashset")] + pub connector_list: HashSet<api_models::enums::Connector>, +} + #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodsForMandate( pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 14f650127dd..188eeeddc10 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -275,6 +275,7 @@ impl PaymentMethodInterface for MockDb { connector_mandate_details: payment_method_new.connector_mandate_details, customer_acceptance: payment_method_new.customer_acceptance, status: payment_method_new.status, + network_transaction_id: payment_method_new.network_transaction_id, }; payment_methods.push(payment_method.clone()); Ok(payment_method) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 72eb6f25559..a2d2648133b 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -277,6 +277,9 @@ wildcard_origin = false card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [analytics] source = "sqlx" diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/down.sql b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql new file mode 100644 index 00000000000..4cf99815a9b --- /dev/null +++ b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE payment_methods DROP COLUMN network_transaction_id; \ No newline at end of file diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/up.sql b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql new file mode 100644 index 00000000000..06b199e6390 --- /dev/null +++ b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE payment_methods ADD COLUMN network_transaction_id VARCHAR(255) DEFAULT NULL; \ No newline at end of file
2024-03-07T11:34:54Z
## Description <!-- Describe your changes in detail --> Add `network_transaction_id` column in the `payment_methods` table as it is required to store the NRID against the respective payment_method_id. This NRID will later be used processor agnostic MITs. This pr also adds application level config (`network_transactoin_id_supported_connectors`) that contains the list of connectors that support the `network_transaction_id`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> columns in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ee1f3540-7c55-4484-b841-9c85696a1a59)
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
columns in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ee1f3540-7c55-4484-b841-9c85696a1a59)
[ "config/deployments/integration_test.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/diesel_models/src/payment_method.rs", "crates/diesel_models/src/schema.rs", "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/se...
juspay/hyperswitch
juspay__hyperswitch-3986
Bug: Create a new column in PM table to store NRID **Schema changes** `network_transaction_id` column needs to be created in the `payment_methods` table to store the NTID / NRID for all the required payment method.
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 77040f79a4a..67dfddd0d55 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -129,6 +129,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay" card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8ae12dc54a6..03dc7825222 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -128,6 +128,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay" card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/development.toml b/config/development.toml index 8ba5c076071..5cdd5f0b9bf 100644 --- a/config/development.toml +++ b/config/development.toml @@ -511,6 +511,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" } card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index eb32b47e3b4..1077bf34c02 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -381,6 +381,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" } card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [connector_customer] connector_list = "gocardless,stax,stripe" payout_connector_list = "wise" diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index ef153c23a7b..681a57bda87 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -38,6 +38,7 @@ pub struct PaymentMethod { pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, + pub network_transaction_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)] @@ -69,6 +70,7 @@ pub struct PaymentMethodNew { pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, + pub network_transaction_id: Option<String>, } impl Default for PaymentMethodNew { @@ -102,6 +104,7 @@ impl Default for PaymentMethodNew { connector_mandate_details: Option::default(), customer_acceptance: Option::default(), status: storage_enums::PaymentMethodStatus::Active, + network_transaction_id: Option::default(), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 8e8bf48a538..ad30609a770 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -913,6 +913,8 @@ diesel::table! { customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, + #[max_length = 255] + network_transaction_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 6906b5a3e7a..537f6666c5d 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -335,6 +335,8 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "email")] email: conf.email, mandates: conf.mandates, + network_transaction_id_supported_connectors: conf + .network_transaction_id_supported_connectors, required_fields: conf.required_fields, delayed_session_response: conf.delayed_session_response, webhook_source_verification_call: conf.webhook_source_verification_call, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index d92812cee40..a0dce991295 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -91,6 +91,7 @@ pub struct Settings<S: SecretState> { pub email: EmailSettings, pub cors: CorsSettings, pub mandates: Mandates, + pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, @@ -251,6 +252,12 @@ pub struct Mandates { pub update_mandate_supported: SupportedPaymentMethodsForMandate, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct NetworkTransactionIdSupportedConnectors { + #[serde(deserialize_with = "deserialize_hashset")] + pub connector_list: HashSet<api_models::enums::Connector>, +} + #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodsForMandate( pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 14f650127dd..188eeeddc10 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -275,6 +275,7 @@ impl PaymentMethodInterface for MockDb { connector_mandate_details: payment_method_new.connector_mandate_details, customer_acceptance: payment_method_new.customer_acceptance, status: payment_method_new.status, + network_transaction_id: payment_method_new.network_transaction_id, }; payment_methods.push(payment_method.clone()); Ok(payment_method) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 72eb6f25559..a2d2648133b 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -277,6 +277,9 @@ wildcard_origin = false card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" + [analytics] source = "sqlx" diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/down.sql b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql new file mode 100644 index 00000000000..4cf99815a9b --- /dev/null +++ b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE payment_methods DROP COLUMN network_transaction_id; \ No newline at end of file diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/up.sql b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql new file mode 100644 index 00000000000..06b199e6390 --- /dev/null +++ b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE payment_methods ADD COLUMN network_transaction_id VARCHAR(255) DEFAULT NULL; \ No newline at end of file
2024-03-07T11:34:54Z
## Description <!-- Describe your changes in detail --> Add `network_transaction_id` column in the `payment_methods` table as it is required to store the NRID against the respective payment_method_id. This NRID will later be used processor agnostic MITs. This pr also adds application level config (`network_transactoin_id_supported_connectors`) that contains the list of connectors that support the `network_transaction_id`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> columns in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ee1f3540-7c55-4484-b841-9c85696a1a59)
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
columns in the `payment_methods` table ![image](https://github.com/juspay/hyperswitch/assets/83439957/ee1f3540-7c55-4484-b841-9c85696a1a59)
[ "config/deployments/integration_test.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/diesel_models/src/payment_method.rs", "crates/diesel_models/src/schema.rs", "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/se...
juspay/hyperswitch
juspay__hyperswitch-4002
Bug: ci: add a step in `check-msrv` get the rust version from `Cargo.toml` In the CI-pr workflow we had hardcoded rust-version to be installed for the check-msrv. This pr adds a step to get rust version from Cargo.toml.
2024-03-07T07:54:56Z
## Description <!-- Describe your changes in detail --> In the `CI-pr` workflow we had hardcoded `rust-version` to be installed for the `check-msrv`. This pr adds a step to get rust version from `Cargo.toml`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> `Check compilation on MSRV toolchain (ubuntu-latest)` has run successfully on this pr. No other testing required.
6671bff3b11e9548a0085046d2594cad9f2571e2
`Check compilation on MSRV toolchain (ubuntu-latest)` has run successfully on this pr. No other testing required.
[]
juspay/hyperswitch
juspay__hyperswitch-4000
Bug: fix: revert mget use authorization In the hosted environment, where we have multiple redis clusters `mget` is not working as expected and throwing the following error: `Unknown Error: CROSSSLOT Keys in request don't hash to the same slot`. Temporary fix is to revert the PR which is using `mget`
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index b5cdcaf0840..2ee8302be63 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -80,25 +80,19 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>( .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) } -pub async fn check_user_and_role_in_blacklist<A: AppStateInfo>( +pub async fn check_role_in_blacklist<A: AppStateInfo>( state: &A, - user_id: &str, role_id: &str, token_expiry: u64, ) -> RouterResult<bool> { - let user_token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); - let role_token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); + let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; - - Ok(redis_conn - .get_multiple_keys::<Vec<&str>, i64>(vec![user_token.as_str(), role_token.as_str()]) + redis_conn + .get_key::<Option<i64>>(token.as_str()) .await - .change_context(ApiErrorResponse::InternalServerError)? - .into_iter() - .max() - .flatten() - .map_or(false, |timestamp| timestamp > token_issued_at)) + .change_context(ApiErrorResponse::InternalServerError) + .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) } #[cfg(feature = "email")] @@ -156,7 +150,10 @@ impl BlackList for AuthToken { where A: AppStateInfo + Sync, { - check_user_and_role_in_blacklist(state, &self.user_id, &self.role_id, self.exp).await + Ok( + check_user_in_blacklist(state, &self.user_id, self.exp).await? + || check_role_in_blacklist(state, &self.role_id, self.exp).await?, + ) } }
2024-03-07T07:29:36Z
## Description `mget` is not working in the hosted version. So, this PR will revert the #3945 which uses `mget``. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context closes #4000 ## How did you test it? Authentication and authorization should work as expected. 1. Signin with any user ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email", "password": "password" }' ``` Response: ``` { "token": JWT, "merchant_id": "merchant_id", "name": "user name" "email": "user email", "verification_days_left": null, "user_role": "org_admin" } ``` 2. Try to hit any api which uses token. ``` curl --location 'http://localhost:8080/user/role/list?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response: ``` [ { "role_id": "merchant_view_only", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "view_only", "role_scope": "organization" }, { "role_id": "merchant_operator", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "operator", "role_scope": "organization" }, { "role_id": "merchant_admin", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage" ], "role_name": "admin", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "groups": [ "operations_view", "analytics_view", "users_view", "users_manage", "merchant_details_view" ], "role_name": "iam", "role_scope": "organization" }, { "role_id": "merchant_developer", "groups": [ "operations_view", "connectors_view", "analytics_view", "users_view", "merchant_details_view", "merchant_details_manage" ], "role_name": "developer", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "customer_support", "role_scope": "organization" } ] ```
6671bff3b11e9548a0085046d2594cad9f2571e2
Authentication and authorization should work as expected. 1. Signin with any user ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email", "password": "password" }' ``` Response: ``` { "token": JWT, "merchant_id": "merchant_id", "name": "user name" "email": "user email", "verification_days_left": null, "user_role": "org_admin" } ``` 2. Try to hit any api which uses token. ``` curl --location 'http://localhost:8080/user/role/list?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response: ``` [ { "role_id": "merchant_view_only", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "view_only", "role_scope": "organization" }, { "role_id": "merchant_operator", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "operator", "role_scope": "organization" }, { "role_id": "merchant_admin", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage" ], "role_name": "admin", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "groups": [ "operations_view", "analytics_view", "users_view", "users_manage", "merchant_details_view" ], "role_name": "iam", "role_scope": "organization" }, { "role_id": "merchant_developer", "groups": [ "operations_view", "connectors_view", "analytics_view", "users_view", "merchant_details_view", "merchant_details_manage" ], "role_name": "developer", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "customer_support", "role_scope": "organization" } ] ```
[ "crates/router/src/services/authentication/blacklist.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3995
Bug: [BUG] Outgoing webhook retry scheduler tasks remain in pending state if merchant webhook URL is not configured ### Bug Description In the outgoing webhook retry process tracker (scheduler) workflow introduced in #3842, the process tracker entries added before the webhook is attempted to be delivered remain in the `process_started` status and `Pending` business status, if either: 1. The `webhook_details` field is not provided in the business profile (or merchant account with default profile). 2. The `webhook_details` is provided but the `webhook_url` within the `webhook_details` object is not provided. 3. The business profile initially had a webhoook URL configured but the profile was updated later to remove the webhook URL (or webhook details). Since in any of the above cases the URL to deliver the webhook to the merchant is unavailable, the task can be aborted. Another optimization is to not create the outgoing webhook event (in the `events` database table) at all, if the merchant webhook URL is not available. ### Expected Behavior - The event (and corresponding process tracker task) should not be created in the `events` table if the merchant webhook URL has not been configured. - In case the business profile initially had a webhook URL configured and was later removed from the business profile, the retry tasks for previously failed webhooks should be aborted. ### Actual Behavior The process tracker task remains in the `process_started` status and `Pending` business status. ### Steps To Reproduce 1. Create a merchant account without the `webhook_details` object or without the `webhook_url` field, using the API. 2. Create an API key, and create a merchant connector account. 3. Make a successful payment. 4. Query the `process_tracker` table in the database to search for workflows with the runner `OUTGOING_WEBHOOK_RETRY_WORKFLOW` and having the payment ID in the name: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%pay_1234%'; ``` The `status` is `process_started` and the `business_status` of the task is `Pending`.
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 968181061a8..609337744d1 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -259,45 +259,44 @@ pub enum WebhooksFlowError { #[error("Webhook details for merchant not configured")] MerchantWebhookDetailsNotFound, #[error("Merchant does not have a webhook URL configured")] - MerchantWebhookURLNotConfigured, - #[error("Payments core flow failed")] - PaymentsCoreFailed, - #[error("Refunds core flow failed")] - RefundsCoreFailed, - #[error("Dispuste core flow failed")] - DisputeCoreFailed, - #[error("Webhook event creation failed")] - WebhookEventCreationFailed, + MerchantWebhookUrlNotConfigured, #[error("Webhook event updation failed")] WebhookEventUpdationFailed, #[error("Outgoing webhook body signing failed")] OutgoingWebhookSigningFailed, - #[error("Unable to fork webhooks flow for outgoing webhooks")] - ForkFlowFailed, #[error("Webhook api call to merchant failed")] CallToMerchantFailed, #[error("Webhook not received by merchant")] NotReceivedByMerchant, - #[error("Resource not found")] - ResourceNotFound, - #[error("Webhook source verification failed")] - WebhookSourceVerificationFailed, - #[error("Webhook event object creation failed")] - WebhookEventObjectCreationFailed, - #[error("Not implemented")] - NotImplemented, #[error("Dispute webhook status validation failed")] DisputeWebhookValidationFailed, #[error("Outgoing webhook body encoding failed")] OutgoingWebhookEncodingFailed, - #[error("Missing required field: {field_name}")] - MissingRequiredField { field_name: &'static str }, #[error("Failed to update outgoing webhook process tracker task")] OutgoingWebhookProcessTrackerTaskUpdateFailed, #[error("Failed to schedule retry attempt for outgoing webhook")] OutgoingWebhookRetrySchedulingFailed, } +impl WebhooksFlowError { + pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool { + match self { + Self::MerchantConfigNotFound + | Self::MerchantWebhookDetailsNotFound + | Self::MerchantWebhookUrlNotConfigured => false, + + Self::WebhookEventUpdationFailed + | Self::OutgoingWebhookSigningFailed + | Self::CallToMerchantFailed + | Self::NotReceivedByMerchant + | Self::DisputeWebhookValidationFailed + | Self::OutgoingWebhookEncodingFailed + | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed + | Self::OutgoingWebhookRetrySchedulingFailed => true, + } + } +} + #[derive(Debug, thiserror::Error)] pub enum ApplePayDecryptionError { #[error("Failed to base64 decode input data")] diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index b3e04e72f33..8d03bea06cb 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -659,8 +659,21 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( primary_object_type: enums::EventObjectType, content: api::OutgoingWebhookContent, ) -> CustomResult<(), errors::ApiErrorResponse> { - let merchant_id = business_profile.merchant_id.clone(); let event_id = format!("{primary_object_id}_{event_type}"); + + if !state.conf.webhooks.outgoing_enabled + || get_webhook_url_from_business_profile(&business_profile).is_err() + { + logger::debug!( + business_profile_id=%business_profile.profile_id, + %event_id, + "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \ + could not be obtained; skipping outgoing webhooks for event" + ); + return Ok(()); + } + + let merchant_id = business_profile.merchant_id.clone(); let new_event = storage::EventNew { event_id: event_id.clone(), event_type, @@ -688,50 +701,48 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( } }?; - if state.conf.webhooks.outgoing_enabled { - let outgoing_webhook = api::OutgoingWebhook { - merchant_id: merchant_id.clone(), - event_id: event.event_id.clone(), - event_type: event.event_type, - content: content.clone(), - timestamp: event.created_at, - }; - - let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker( - &*state.store, - &business_profile, - &event, - ) - .await - .map_err(|error| { - logger::error!( - ?error, - "Failed to add outgoing webhook retry task to process tracker" - ); - error - }) - .ok(); + let outgoing_webhook = api::OutgoingWebhook { + merchant_id: merchant_id.clone(), + event_id: event.event_id.clone(), + event_type: event.event_type, + content: content.clone(), + timestamp: event.created_at, + }; - // Using a tokio spawn here and not arbiter because not all caller of this function - // may have an actix arbiter - tokio::spawn( - async move { - trigger_appropriate_webhook_and_raise_event( - state, - merchant_account, - business_profile, - outgoing_webhook, - types::WebhookDeliveryAttempt::InitialAttempt, - content, - event.event_id, - event_type, - process_tracker, - ) - .await; - } - .in_current_span(), + let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker( + &*state.store, + &business_profile, + &event, + ) + .await + .map_err(|error| { + logger::error!( + ?error, + "Failed to add outgoing webhook retry task to process tracker" ); - } + error + }) + .ok(); + + // Using a tokio spawn here and not arbiter because not all caller of this function + // may have an actix arbiter + tokio::spawn( + async move { + trigger_appropriate_webhook_and_raise_event( + state, + merchant_account, + business_profile, + outgoing_webhook, + types::WebhookDeliveryAttempt::InitialAttempt, + content, + event.event_id, + event_type, + process_tracker, + ) + .await; + } + .in_current_span(), + ); Ok(()) } @@ -817,21 +828,30 @@ async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( delivery_attempt: types::WebhookDeliveryAttempt, process_tracker: Option<storage::ProcessTracker>, ) -> CustomResult<(), errors::WebhooksFlowError> { - let webhook_details_json = business_profile - .webhook_details - .get_required_value("webhook_details") - .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; - - let webhook_details: api::WebhookDetails = - webhook_details_json - .parse_value("WebhookDetails") - .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; - - let webhook_url = webhook_details - .webhook_url - .get_required_value("webhook_url") - .change_context(errors::WebhooksFlowError::MerchantWebhookURLNotConfigured) - .map(ExposeInterface::expose)?; + let webhook_url = match ( + get_webhook_url_from_business_profile(&business_profile), + process_tracker.clone(), + ) { + (Ok(webhook_url), _) => Ok(webhook_url), + (Err(error), Some(process_tracker)) => { + if !error + .current_context() + .is_webhook_delivery_retryable_error() + { + logger::debug!("Failed to obtain merchant webhook URL, aborting retries"); + state + .store + .as_scheduler() + .finish_process_with_business_status(process_tracker, "FAILURE".into()) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, + )?; + } + Err(error) + } + (Err(error), None) => Err(error), + }?; let outgoing_webhook_event_id = webhook.event_id.clone(); @@ -1579,7 +1599,7 @@ pub async fn add_outgoing_webhook_retry_task_to_process_tracker( let process_tracker_id = scheduler::utils::get_process_tracker_id( runner, task, - &event.primary_object_id, + &event.event_id, &business_profile.merchant_id, ); let process_tracker_entry = storage::ProcessTrackerNew::new( @@ -1611,3 +1631,24 @@ pub async fn add_outgoing_webhook_retry_task_to_process_tracker( } } } + +fn get_webhook_url_from_business_profile( + business_profile: &diesel_models::business_profile::BusinessProfile, +) -> CustomResult<String, errors::WebhooksFlowError> { + let webhook_details_json = business_profile + .webhook_details + .clone() + .get_required_value("webhook_details") + .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; + + let webhook_details: api::WebhookDetails = + webhook_details_json + .parse_value("WebhookDetails") + .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; + + webhook_details + .webhook_url + .get_required_value("webhook_url") + .change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured) + .map(ExposeInterface::expose) +}
2024-03-06T20:36:25Z
## Description <!-- Describe your changes in detail --> This PR fixes a bug in the outgoing webhook retry workflow where process tracker tasks remained in pending state if merchant webhook URL was not configured in the business profile. For more information, see: #3995. In addition, this PR includes these changes: 1. Updates the process tracker task ID format to include the event ID instead of the primary resource ID. 2. Removes unused enum variants from the `WebhooksFlowError` error enum. The PR can easily be reviewed one commit at a time. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #3995. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Locally, by running `router`, `producer` and `consumer`, and testing for these three cases: 1. For a business profile with webhook URL configured, the behavior should remain as before: webhooks should either be delivered successfully in the first attempt, or scheduled for later retries. 1. Screenshot of a webhook delivered in the initial attempt (business status is `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`): ![Screenshot of webhook delivery attempt successful in the first try](https://github.com/juspay/hyperswitch/assets/22217505/04426f89-4718-476c-970f-a78cfcc33422) 2. Screenshot of a webhook delivered during a retry attempt (business status is `COMPLETED_BY_PT` and retry count is positive): ![Screenshot of webhook delivery attempt successful during retry](https://github.com/juspay/hyperswitch/assets/22217505/3ecbfe60-140a-4a01-a5ef-eb6ce6bd7ab0) 2. For a business profile without `webhook_url` (or `webhook_details`) configured, the event is not created in the `events` table (and no process tracker task), and the `router` service displays a log line about the same: ![Screenshot of log message indicating failure in retrieving merchant webhook URL](https://github.com/juspay/hyperswitch/assets/22217505/d9eca15e-5731-4fde-a418-cbfd7148d39d) The absence of the event in the `events` table and the process tracker task in the `process_tracker` table can be confirmed using the SQL queries, no rows should be returned in either case: ```sql SELECT * FROM events WHERE event_id = 'event_id'; SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%event_id%'; ``` 3. For a business profile with a webhook URL configured initially but later updated to not include the `webhook_url` field or the `webhook_details` object, the task is aborted by the consumer: 1. The business status is `FAILURE`, and retry count is positive: ![Screenshot of task aborted during a retry attempt](https://github.com/juspay/hyperswitch/assets/22217505/2b968190-397e-4679-b98e-227a59d0ff23) 2. In addition, the `consumer` service displays a log line about the task being aborted. ![Screenshot of log message indicating task being aborted](https://github.com/juspay/hyperswitch/assets/22217505/0cec108a-d37f-4b2c-9a36-b2425527f58c) The process tracker tasks in the above cases can be queried by using the SQL command, substituting the resource ID: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%pay_1234%'; ```
0aa40cbae75fd4cf5b13cfc518ff761b2b673246
Locally, by running `router`, `producer` and `consumer`, and testing for these three cases: 1. For a business profile with webhook URL configured, the behavior should remain as before: webhooks should either be delivered successfully in the first attempt, or scheduled for later retries. 1. Screenshot of a webhook delivered in the initial attempt (business status is `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`): ![Screenshot of webhook delivery attempt successful in the first try](https://github.com/juspay/hyperswitch/assets/22217505/04426f89-4718-476c-970f-a78cfcc33422) 2. Screenshot of a webhook delivered during a retry attempt (business status is `COMPLETED_BY_PT` and retry count is positive): ![Screenshot of webhook delivery attempt successful during retry](https://github.com/juspay/hyperswitch/assets/22217505/3ecbfe60-140a-4a01-a5ef-eb6ce6bd7ab0) 2. For a business profile without `webhook_url` (or `webhook_details`) configured, the event is not created in the `events` table (and no process tracker task), and the `router` service displays a log line about the same: ![Screenshot of log message indicating failure in retrieving merchant webhook URL](https://github.com/juspay/hyperswitch/assets/22217505/d9eca15e-5731-4fde-a418-cbfd7148d39d) The absence of the event in the `events` table and the process tracker task in the `process_tracker` table can be confirmed using the SQL queries, no rows should be returned in either case: ```sql SELECT * FROM events WHERE event_id = 'event_id'; SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%event_id%'; ``` 3. For a business profile with a webhook URL configured initially but later updated to not include the `webhook_url` field or the `webhook_details` object, the task is aborted by the consumer: 1. The business status is `FAILURE`, and retry count is positive: ![Screenshot of task aborted during a retry attempt](https://github.com/juspay/hyperswitch/assets/22217505/2b968190-397e-4679-b98e-227a59d0ff23) 2. In addition, the `consumer` service displays a log line about the task being aborted. ![Screenshot of log message indicating task being aborted](https://github.com/juspay/hyperswitch/assets/22217505/0cec108a-d37f-4b2c-9a36-b2425527f58c) The process tracker tasks in the above cases can be queried by using the SQL command, substituting the resource ID: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%pay_1234%'; ```
[ "crates/router/src/core/errors.rs", "crates/router/src/core/webhooks.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3979
Bug: Setup-future-usage to be defaulted to on-session
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 76893659e03..2bcd317bafc 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3865,7 +3865,10 @@ pub fn validate_mandate_data_and_future_usage( setup_future_usages: Option<api_enums::FutureUsage>, mandate_details_present: bool, ) -> Result<(), errors::ApiErrorResponse> { - if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present { + if mandate_details_present + && (Some(api_enums::FutureUsage::OnSession) == setup_future_usages + || setup_future_usages.is_none()) + { Err(errors::ApiErrorResponse::PreconditionFailed { message: "`setup_future_usage` must be `off_session` for mandates".into(), }) diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 3a7ab7d9abe..c085382232b 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -102,9 +102,7 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; - let pm_id = if resp.request.get_setup_future_usage().is_some() - && customer_acceptance.is_some() - { + let pm_id = if customer_acceptance.is_some() { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()),
2024-03-06T14:13:15Z
## Description accept customer_acceptance to save the card ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create an MA and an MCA - Do a save card payment only by passing customer_acceptance -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \ --data-raw ' {"amount": 7000, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "77cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_ir21sZA1B2FN8Vn1zYT8/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \ --data '{ "confirm": true, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }} }' ``` - the card will be saved , irrespective of the setup_future_usage <img width="2170" alt="Screenshot 2024-03-07 at 5 19 41 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/7907b2a1-2442-4986-b01f-9040dee2be1f">
9bee5ab3f10d7d7c832c2ba5c4990bd85af32928
- Create an MA and an MCA - Do a save card payment only by passing customer_acceptance -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \ --data-raw ' {"amount": 7000, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "77cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_ir21sZA1B2FN8Vn1zYT8/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \ --data '{ "confirm": true, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }} }' ``` - the card will be saved , irrespective of the setup_future_usage <img width="2170" alt="Screenshot 2024-03-07 at 5 19 41 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/7907b2a1-2442-4986-b01f-9040dee2be1f">
[ "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/tokenization.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3766
Bug: Insert `payment_method_id` in redis for wallet tokens To be discussed: In case of wallets, banks what should be the Payment Token equivalent? Note: Update last_used field
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index df1fb1e358d..220a28771c8 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -192,6 +192,8 @@ impl PaymentMethodRetrieve for Oss { ) .await } + + storage::PaymentTokenData::WalletToken(_) => Ok(None), } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4fdf957c842..0e45f689d12 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2757,6 +2757,12 @@ pub async fn list_customer_payment_method( } } + enums::PaymentMethod::Wallet => ( + None, + None, + PaymentTokenData::wallet_token(pm.payment_method_id.clone()), + ), + _ => ( None, None, diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index a787a4d932c..17d31ff353d 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -23,6 +23,11 @@ pub struct GenericTokenData { pub token: String, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct WalletTokenData { + pub payment_method_id: String, +} + #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PaymentTokenData { @@ -33,6 +38,7 @@ pub enum PaymentTokenData { Permanent(CardTokenData), PermanentCard(CardTokenData), AuthBankDebit(payment_methods::BankAccountConnectorDetails), + WalletToken(WalletTokenData), } impl PaymentTokenData { @@ -51,4 +57,8 @@ impl PaymentTokenData { pub fn temporary_generic(token: String) -> Self { Self::TemporaryGeneric(GenericTokenData { token }) } + + pub fn wallet_token(payment_method_id: String) -> Self { + Self::WalletToken(WalletTokenData { payment_method_id }) + } }
2024-03-06T12:54:20Z
## Description <!-- Describe your changes in detail --> This PR adds support for wallet tokens to be inserted in redis with value being `payment_method_id` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create mca with wallets being a payment method ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "custhype1232", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"data", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "identifier" } } } }' ``` 3. Check whether payment_methods entry is created in table 4. Now do `list_customer_payment_method` which generates a payment_token When checked in redis for that `payment_token` ![image](https://github.com/juspay/hyperswitch/assets/70657455/95662ab4-fa17-413f-8255-08a65fcb6c83) Cannot be tested in sandbox, as this inserts value in redis. (Could log into redis and check the entry)
d220e815dc81925b205fb57d5d4f05883c1a7cde
1. Create mca with wallets being a payment method ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "custhype1232", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"data", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "identifier" } } } }' ``` 3. Check whether payment_methods entry is created in table 4. Now do `list_customer_payment_method` which generates a payment_token When checked in redis for that `payment_token` ![image](https://github.com/juspay/hyperswitch/assets/70657455/95662ab4-fa17-413f-8255-08a65fcb6c83) Cannot be tested in sandbox, as this inserts value in redis. (Could log into redis and check the entry)
[ "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/types/storage/payment_method.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3987
Bug: feat: get specific user role details api Currently frontend is using the user list api to get the details of the users in a particular merchant account. If somebody is in a user details page and refreshes, FE will again call list api to get the details as there is no api to get the details of a specific user.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index ec3e2dce9b2..4ef04981572 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -11,11 +11,11 @@ use crate::user::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, - CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, - InviteUserRequest, InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, - SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, - SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate, - VerifyEmailRequest, + CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, + GetUserDetailsRequest, GetUserDetailsResponse, InviteUserRequest, InviteUserResponse, + ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest, + SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, + UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -48,7 +48,7 @@ common_utils::impl_misc_api_event_type!( SwitchMerchantIdRequest, CreateInternalUserRequest, UserMerchantCreate, - GetUsersResponse, + ListUsersResponse, AuthorizeResponse, ConnectAccountRequest, ForgotPasswordRequest, @@ -60,7 +60,9 @@ common_utils::impl_misc_api_event_type!( SendVerifyEmailRequest, AcceptInviteFromEmailRequest, SignInResponse, - UpdateUserAccountDetailsRequest + UpdateUserAccountDetailsRequest, + GetUserDetailsRequest, + GetUserDetailsResponse ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 8f77f72aad5..0db711f5eca 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,3 +1,4 @@ +use common_enums::{PermissionGroup, RoleScope}; use common_utils::{crypto::OptionalEncryptableName, pii}; use masking::Secret; @@ -143,7 +144,7 @@ pub struct UserMerchantCreate { } #[derive(Debug, serde::Serialize)] -pub struct GetUsersResponse(pub Vec<UserDetails>); +pub struct ListUsersResponse(pub Vec<UserDetails>); #[derive(Debug, serde::Serialize)] pub struct UserDetails { @@ -156,6 +157,24 @@ pub struct UserDetails { pub last_modified_at: time::PrimitiveDateTime, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct GetUserDetailsRequest { + pub email: pii::Email, +} + +#[derive(Debug, serde::Serialize)] +pub struct GetUserDetailsResponse { + 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::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b8b8cbd24c7..6516022cfd7 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1193,10 +1193,53 @@ pub async fn list_merchant_ids_for_user( )) } -pub async fn get_users_for_merchant_account( +pub async fn get_user_details_in_merchant_account( state: AppState, user_from_token: auth::UserFromToken, -) -> UserResponse<user_api::GetUsersResponse> { + request: user_api::GetUserDetailsRequest, +) -> UserResponse<user_api::GetUserDetailsResponse> { + 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, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in the merchant account")?; + + let role_info = roles::RoleInfo::from_role_id( + &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::GetUserDetailsResponse { + 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_users_for_merchant_account( + state: AppState, + user_from_token: auth::UserFromToken, +) -> UserResponse<user_api::ListUsersResponse> { let users_and_user_roles = state .store .find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str()) @@ -1235,7 +1278,7 @@ pub async fn get_users_for_merchant_account( }) .collect(); - Ok(ApplicationResponse::Json(user_api::GetUsersResponse( + Ok(ApplicationResponse::Json(user_api::ListUsersResponse( user_details_vec, ))) } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 73558c78d7b..b37e034d8db 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1115,7 +1115,10 @@ impl User { // User management route = route.service( web::scope("/user") - .service(web::resource("/list").route(web::get().to(get_user_details))) + .service(web::resource("").route(web::get().to(get_user_role_details))) + .service( + web::resource("/list").route(web::get().to(list_users_for_merchant_account)), + ) .service(web::resource("/invite").route(web::post().to(invite_user))) .service( web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9471289a0c8..897b33266b8 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -182,6 +182,7 @@ impl From<Flow> for ApiIdentifier { | Flow::DeleteSampleData | Flow::UserMerchantAccountList | Flow::GetUserDetails + | Flow::ListUsersForMerchantAccount | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 0568b31338b..3c10ce38f9f 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -314,14 +314,35 @@ pub async fn list_merchant_ids_for_user( .await } -pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn get_user_role_details( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Query<user_api::GetUserDetailsRequest>, +) -> 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::UsersRead), + api_locking::LockAction::NotApplicable, + )) + .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::get_users_for_merchant_account(state, user), + |state, user, _| user_core::list_users_for_merchant_account(state, user), &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 62c09c42455..b4adc077af1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -330,8 +330,10 @@ pub enum Flow { DeleteSampleData, /// List merchant accounts for user UserMerchantAccountList, - /// Get users for merchant account + /// Get details of a user in a merchant account GetUserDetails, + /// List users for merchant account + ListUsersForMerchantAccount, /// PaymentMethodAuth Link token create PmAuthLinkTokenCreate, /// PaymentMethodAuth Exchange token create
2024-03-06T12:39:09Z
## Description <!-- Describe your changes in detail --> Currently there is no way to get the details of user and their role directly. This API solves it by taking the email of the user and returns the details. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes [#3987](https://github.com/juspay/hyperswitch/issues/3987) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman. ``` curl --location 'http://localhost:8080/user/user?email=user@hyperswitch.io' \ --header 'Authorization: Bearer JWT' ``` ``` { "email": "user email", "name": "user name", "role_id": "merchant_view_only", "role_name": "View Only", "status": "Active", "last_modified_at": "2024-03-01T06:23:44.250Z", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_scope": "organization" } ```
2db39e8bb9af3d55e3d075d77ff8616ee2e15f0a
Postman. ``` curl --location 'http://localhost:8080/user/user?email=user@hyperswitch.io' \ --header 'Authorization: Bearer JWT' ``` ``` { "email": "user email", "name": "user name", "role_id": "merchant_view_only", "role_name": "View Only", "status": "Active", "last_modified_at": "2024-03-01T06:23:44.250Z", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_scope": "organization" } ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3983
Bug: refactor: kms decrypt analytics config Add support for kms decrypting the analytics config
diff --git a/Cargo.lock b/Cargo.lock index 60bc557972c..4571d80fd87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -349,6 +349,7 @@ dependencies = [ "error-stack", "external_services", "futures 0.3.28", + "hyperswitch_interfaces", "masking", "once_cell", "reqwest", diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 82ac2dde030..f3e01492135 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -11,8 +11,9 @@ edition = "2021" # First party crates api_models = { version = "0.1.0", path = "../api_models" , features = ["errors"]} storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } -common_utils = { version = "0.1.0", path = "../common_utils"} -external_services = { version = "0.1.0", path = "../external_services", default-features = false} +common_utils = { version = "0.1.0", path = "../common_utils" } +external_services = { version = "0.1.0", path = "../external_services", default-features = false } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } masking = { version = "0.1.0", path = "../masking" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index c9752bd27a6..d8de32a732b 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -15,7 +15,13 @@ pub mod sdk_events; mod sqlx; mod types; use api_event::metrics::{ApiEventMetric, ApiEventMetricRow}; +use common_utils::errors::CustomResult; use disputes::metrics::{DisputeMetric, DisputeMetricRow}; +use hyperswitch_interfaces::secrets_interface::{ + secret_handler::SecretsHandler, + secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, + SecretManagementInterface, SecretsManagementError, +}; pub use types::AnalyticsDomain; pub mod lambda_utils; pub mod utils; @@ -598,6 +604,51 @@ pub enum AnalyticsConfig { }, } +#[async_trait::async_trait] +impl SecretsHandler for AnalyticsConfig { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let analytics_config = value.get_inner(); + let decrypted_password = match analytics_config { + // Todo: Perform kms decryption of clickhouse password + Self::Clickhouse { .. } => masking::Secret::new(String::default()), + Self::Sqlx { sqlx } + | Self::CombinedCkh { sqlx, .. } + | Self::CombinedSqlx { sqlx, .. } => { + secret_management_client + .get_secret(sqlx.password.clone()) + .await? + } + }; + + Ok(value.transition_state(|conf| match conf { + Self::Sqlx { sqlx } => Self::Sqlx { + sqlx: Database { + password: decrypted_password, + ..sqlx + }, + }, + Self::Clickhouse { clickhouse } => Self::Clickhouse { clickhouse }, + Self::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh { + sqlx: Database { + password: decrypted_password, + ..sqlx + }, + clickhouse, + }, + Self::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx { + sqlx: Database { + password: decrypted_password, + ..sqlx + }, + clickhouse, + }, + })) + } +} + impl Default for AnalyticsConfig { fn default() -> Self { Self::Sqlx { diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index bbcc2b5bceb..f89d1811988 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -233,6 +233,13 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt master database configuration"); + #[cfg(feature = "olap")] + #[allow(clippy::expect_used)] + let analytics = + analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client) + .await + .expect("Failed to decrypt analytics configuration"); + #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let replica_database = @@ -342,7 +349,7 @@ pub(crate) async fn fetch_raw_secrets( temp_locker_enable_config: conf.temp_locker_enable_config, payment_link: conf.payment_link, #[cfg(feature = "olap")] - analytics: conf.analytics, + analytics, #[cfg(feature = "kv_store")] kv_config: conf.kv_config, #[cfg(feature = "frm")] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 00897951ba8..70a173f1d95 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -105,7 +105,7 @@ pub struct Settings<S: SecretState> { pub temp_locker_enable_config: TempLockerEnableConfig, pub payment_link: PaymentLink, #[cfg(feature = "olap")] - pub analytics: AnalyticsConfig, + pub analytics: SecretStateContainer<AnalyticsConfig, S>, #[cfg(feature = "kv_store")] pub kv_config: KvConfig, #[cfg(feature = "frm")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1d82bc7539f..798b07d149f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -200,7 +200,8 @@ impl AppState { }; #[cfg(feature = "olap")] - let pool = crate::analytics::AnalyticsProvider::from_conf(&conf.analytics).await; + let pool = + crate::analytics::AnalyticsProvider::from_conf(conf.analytics.get_inner()).await; #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await);
2024-03-06T11:53:38Z
## Description <!-- Describe your changes in detail --> This PR adds support for kms decrypting the analytics config ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Locally set up aws kms and decryption of analytics config was successful. Currently Sandbox uses clickhouse setup, so this PR cannot be tested. Can be deployed in custom pod by using Sqlx there.
2db39e8bb9af3d55e3d075d77ff8616ee2e15f0a
Locally set up aws kms and decryption of analytics config was successful. Currently Sandbox uses clickhouse setup, so this PR cannot be tested. Can be deployed in custom pod by using Sqlx there.
[ "Cargo.lock", "crates/analytics/Cargo.toml", "crates/analytics/src/lib.rs", "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/settings.rs", "crates/router/src/routes/app.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3980
Bug: [FEATURE] [AUTHORIZEDOTNET] Pass billing address details ### Feature Description Billing Address needs to be passed in payments request. ### Possible Implementation Billing Address needs to be passed in BillTo field of payments request for connector authorizedotnet. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 8ba610d66d4..2d6f2e040a4 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -7,10 +7,17 @@ use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData}, + connector::utils::{ + self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData, + }, core::errors, services, - types::{self, api, storage::enums, transformers::ForeignFrom}, + types::{ + self, + api::{self, enums as api_enums}, + storage::enums, + transformers::ForeignFrom, + }, utils::OptionExt, }; @@ -231,6 +238,8 @@ struct TransactionRequest { amount: f64, currency_code: String, payment: PaymentDetails, + order: Order, + bill_to: Option<BillTo>, processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, @@ -243,6 +252,24 @@ pub struct ProcessingOptions { is_subsequent_auth: bool, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BillTo { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address: Option<Secret<String>>, + city: Option<String>, + state: Option<Secret<String>>, + zip: Option<Secret<String>>, + country: Option<api_enums::CountryAlpha2>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Order { + description: String, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SubsequentAuthInformation { @@ -341,12 +368,27 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> }), None => None, }; - + let bill_to = item + .router_data + .get_billing_address_details_as_optional() + .map(|address| BillTo { + first_name: address.first_name.clone(), + last_name: address.last_name.clone(), + address: address.line1.clone(), + city: address.city.clone(), + state: address.state.clone(), + zip: address.zip.clone(), + country: address.country, + }); let transaction_request = TransactionRequest { transaction_type: TransactionType::from(item.router_data.request.capture_method), amount: item.amount, - payment: payment_details, currency_code: item.router_data.request.currency.to_string(), + payment: payment_details, + order: Order { + description: item.router_data.connector_request_reference_id.clone(), + }, + bill_to, processing_options, subsequent_auth_information, authorization_indicator_type,
2024-03-06T11:08:36Z
## Description <!-- Describe your changes in detail --> - If the billing address is included in the payments request, it will be transmitted to the connector. - Additionally, the `connector_request_reference_id` is now transmitted within the order description, making it visible in the transaction details on the connector dashboard. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3980 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test payments (manual and automatic) for authorizedotnet. 1. Automatic: - Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` - Response: ```json { "payment_id": "pay_cuLkCdbQQzkHymq2TKDU", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": 1234, "connector": "authorizedotnet", "client_secret": "pay_cuLkCdbQQzkHymq2TKDU_secret_F8avCQMZYy6Ayy6KUeQd", "created": "2024-03-06T11:14:34.973Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709723674, "expires": 1709727274, "secret": "epk_6a7570ed25eb463d91972aa3c5a6cca6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015569706", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569706", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:29:34.973Z", "fingerprint": null } ``` 2. Manual: - Authorize request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` - Authorize Response: ```json { "payment_id": "pay_GCVt2jy4rwpznGCPVpvs", "merchant_id": "merchant_1709720492", "status": "requires_capture", "amount": 1234, "net_amount": 1234, "amount_capturable": 1234, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB", "created": "2024-03-06T11:16:02.569Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709723762, "expires": 1709727362, "secret": "epk_cc979868f4114736aa643b628b57c171" }, "manual_retry_allowed": false, "connector_transaction_id": "80015569729", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569729", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:31:02.569Z", "fingerprint": null } ``` - Capture Request: ```curl curl --location 'http://localhost:8080/payments/pay_GCVt2jy4rwpznGCPVpvs/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` - Capture Response: ```json { "payment_id": "pay_GCVt2jy4rwpznGCPVpvs", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": 1234, "connector": "authorizedotnet", "client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB", "created": "2024-03-06T11:16:02.569Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015569729", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569729", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:31:02.569Z", "fingerprint": null } ``` For all the mentioned scenarios, both the billing address and the connector_request_reference_id should be visible on the Authorized.net dashboard. <img width="596" alt="Screenshot 2024-03-06 at 4 14 57 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/9a70dbea-98d8-4695-9b28-00c4e20a9c3b"> NOTE: In all the mentioned scenarios, attempt submitting partial billing addresses, and at times, no billing address at all, ensuring that all payment transactions still function correctly.
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
Test payments (manual and automatic) for authorizedotnet. 1. Automatic: - Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` - Response: ```json { "payment_id": "pay_cuLkCdbQQzkHymq2TKDU", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": 1234, "connector": "authorizedotnet", "client_secret": "pay_cuLkCdbQQzkHymq2TKDU_secret_F8avCQMZYy6Ayy6KUeQd", "created": "2024-03-06T11:14:34.973Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709723674, "expires": 1709727274, "secret": "epk_6a7570ed25eb463d91972aa3c5a6cca6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015569706", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569706", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:29:34.973Z", "fingerprint": null } ``` 2. Manual: - Authorize request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5424000000000015", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } }, "setup_future_usage": "on_session" }' ``` - Authorize Response: ```json { "payment_id": "pay_GCVt2jy4rwpznGCPVpvs", "merchant_id": "merchant_1709720492", "status": "requires_capture", "amount": 1234, "net_amount": 1234, "amount_capturable": 1234, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB", "created": "2024-03-06T11:16:02.569Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709723762, "expires": 1709727362, "secret": "epk_cc979868f4114736aa643b628b57c171" }, "manual_retry_allowed": false, "connector_transaction_id": "80015569729", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569729", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:31:02.569Z", "fingerprint": null } ``` - Capture Request: ```curl curl --location 'http://localhost:8080/payments/pay_GCVt2jy4rwpznGCPVpvs/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` - Capture Response: ```json { "payment_id": "pay_GCVt2jy4rwpznGCPVpvs", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": 1234, "connector": "authorizedotnet", "client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB", "created": "2024-03-06T11:16:02.569Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0015", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "542400", "card_extended_bin": "54240000", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe" }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015569729", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015569729", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "request_external_3ds_authentication": null, "expires_on": "2024-03-06T11:31:02.569Z", "fingerprint": null } ``` For all the mentioned scenarios, both the billing address and the connector_request_reference_id should be visible on the Authorized.net dashboard. <img width="596" alt="Screenshot 2024-03-06 at 4 14 57 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/9a70dbea-98d8-4695-9b28-00c4e20a9c3b"> NOTE: In all the mentioned scenarios, attempt submitting partial billing addresses, and at times, no billing address at all, ensuring that all payment transactions still function correctly.
[ "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3977
Bug: [BUG]: [Adyen] Webhook Psync response Handler ### Bug Description Currently the Psync response handler for webhook tightly coupled to payments response which is creating a lot of bugs in status and transaction id updates - Update Psync response handler to consume the incoming webhook response - Handle Webhook Status Mapping ### Expected Behavior Decouple the Webhook Response from Payments response and handle all the status and reference ids separately ### Actual Behavior Currently the Psync response handler for webhook tightly coupled to payments response which is creating a lot of bugs in status and transaction id updates - Update Psync response handler to consume the incoming webhook response - Handle Webhook Status Mapping ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 93301364e62..67e319ddc22 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -403,6 +403,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentSession for Adyen {} @@ -516,6 +523,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } /// Payment Sync can be useful only incase of Redirect flow. @@ -681,6 +695,13 @@ impl ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> { Ok(services::CaptureSyncMethod::Individual) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -795,6 +816,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentsPreProcessing for Adyen {} @@ -925,6 +954,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -1022,6 +1059,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Payouts for Adyen {} @@ -1129,6 +1173,13 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1227,6 +1278,13 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1330,6 +1388,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1446,6 +1511,13 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Refund for Adyen {} @@ -1553,6 +1625,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> @@ -1717,7 +1796,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - let response: adyen::Response = notif.into(); + let response = adyen::AdyenWebhookResponse::from(notif); Ok(Box::new(response)) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 9fbf7d99812..c44d590e2f1 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3,7 +3,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; use common_utils::{ext_traits::Encode, pii}; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -24,7 +24,7 @@ use crate::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, PaymentsAuthorizeData, }, utils as crate_utils, @@ -271,6 +271,31 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> } } +impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatus { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + (is_manual_capture, adyen_webhook_status): (bool, AdyenWebhookStatus), + ) -> Result<Self, Self::Error> { + match adyen_webhook_status { + AdyenWebhookStatus::Authorised => match is_manual_capture { + true => Ok(Self::Authorized), + // In case of Automatic capture Authorized is the final status of the payment + false => Ok(Self::Charged), + }, + AdyenWebhookStatus::AuthorisationFailed => Ok(Self::Failure), + AdyenWebhookStatus::Cancelled => Ok(Self::Voided), + AdyenWebhookStatus::CancelFailed => Ok(Self::VoidFailed), + AdyenWebhookStatus::Captured => Ok(Self::Charged), + AdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed), + //If Unexpected Event is received, need to understand how it reached this point + //Webhooks with Payment Events only should try to conume this resource object. + AdyenWebhookStatus::UnexpectedEvent => { + Err(errors::ConnectorError::WebhookBodyDecodingFailed).into_report() + } + } + } +} + #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AdyenRedirectRequest { pub details: AdyenRedirectRequestTypes, @@ -320,6 +345,7 @@ pub enum AdyenPaymentResponse { QrCodeResponse(Box<QrCodeResponseResponse>), RedirectionResponse(Box<RedirectionResponse>), RedirectionErrorResponse(Box<RedirectionErrorResponse>), + WebhookResponse(Box<AdyenWebhookResponse>), } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -332,8 +358,31 @@ pub struct Response { refusal_reason: Option<String>, refusal_reason_code: Option<String>, additional_data: Option<AdditionalData>, - // event_code will be available only in webhook body - event_code: Option<WebhookEventCode>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdyenWebhookStatus { + Authorised, + AuthorisationFailed, + Cancelled, + CancelFailed, + Captured, + CaptureFailed, + UnexpectedEvent, +} + +//Creating custom struct which can be consumed in Psync Handler triggered from Webhooks +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenWebhookResponse { + transaction_id: String, + payment_reference: Option<String>, + status: AdyenWebhookStatus, + amount: Option<Amount>, + merchant_reference_id: String, + refusal_reason: Option<String>, + refusal_reason_code: Option<String>, + event_code: WebhookEventCode, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3091,7 +3140,6 @@ pub fn get_adyen_response( > { let status = storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code, pmt)); - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { Some(types::ErrorResponse { code: response @@ -3135,10 +3183,11 @@ pub fn get_adyen_response( Ok((status, error, payments_response_data)) } -pub fn get_adyen_response_for_multiple_partial_capture( - response: Response, +pub fn get_webhook_response( + response: AdyenWebhookResponse, + is_capture_manual: bool, + is_multiple_capture_psync_flow: bool, status_code: u16, - pmt: Option<enums::PaymentMethodType>, ) -> errors::CustomResult< ( storage_enums::AttemptStatus, @@ -3147,28 +3196,53 @@ pub fn get_adyen_response_for_multiple_partial_capture( ), errors::ConnectorError, > { - let (status, error, _) = get_adyen_response(response.clone(), true, status_code, pmt)?; - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); - let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); - Ok(( - status, - error, - types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - }, - )) -} + let status = storage_enums::AttemptStatus::foreign_try_from(( + is_capture_manual, + response.status.clone(), + ))?; + let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { + Some(types::ErrorResponse { + code: response + .refusal_reason_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response + .refusal_reason + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: response.refusal_reason.clone(), + status_code, + attempt_status: None, + connector_transaction_id: Some(response.transaction_id.clone()), + }) + } else { + None + }; -fn update_attempt_status_based_on_event_type_if_needed( - status: storage_enums::AttemptStatus, - event: &Option<WebhookEventCode>, -) -> storage_enums::AttemptStatus { - if status == storage_enums::AttemptStatus::Authorized - && event == &Some(WebhookEventCode::Capture) - { - storage_enums::AttemptStatus::Charged + if is_multiple_capture_psync_flow { + let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); + Ok(( + status, + error, + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + }, + )) } else { - status + let payments_response_data = types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response + .payment_reference + .unwrap_or(response.transaction_id), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.merchant_reference_id), + incremental_authorization_allowed: None, + }; + Ok((status, error, payments_response_data)) } } @@ -3656,11 +3730,7 @@ impl<F, Req> let is_manual_capture = utils::is_manual_capture(capture_method); let (status, error, payment_response_data) = match item.response { AdyenPaymentResponse::Response(response) => { - if is_multiple_capture_psync_flow { - get_adyen_response_for_multiple_partial_capture(*response, item.http_code, pmt)? - } else { - get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? - } + get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? } AdyenPaymentResponse::PresentToShopper(response) => { get_present_to_shopper_response(*response, is_manual_capture, item.http_code, pmt)? @@ -3674,6 +3744,12 @@ impl<F, Req> AdyenPaymentResponse::RedirectionErrorResponse(response) => { get_redirection_error_response(*response, is_manual_capture, item.http_code, pmt)? } + AdyenPaymentResponse::WebhookResponse(response) => get_webhook_response( + *response, + is_manual_capture, + is_multiple_capture_psync_flow, + item.http_code, + )?, }; Ok(Self { @@ -3893,6 +3969,8 @@ pub enum WebhookEventCode { Refund, CancelOrRefund, Cancellation, + Capture, + CaptureFailed, RefundFailed, RefundReversed, NotificationOfChargeback, @@ -3901,8 +3979,6 @@ pub enum WebhookEventCode { SecondChargeback, PrearbitrationWon, PrearbitrationLost, - Capture, - CaptureFailed, #[serde(other)] Unknown, } @@ -4046,52 +4122,81 @@ pub struct AdyenIncomingWebhook { pub notification_items: Vec<AdyenItemObjectWH>, } -impl From<AdyenNotificationRequestItemWH> for Response { +impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse { fn from(notif: AdyenNotificationRequestItemWH) -> Self { Self { - psp_reference: notif.psp_reference, - merchant_reference: notif.merchant_reference, - result_code: match notif.success.as_str() { - "true" => { - if notif.event_code == WebhookEventCode::Cancellation { - AdyenStatus::Cancelled + transaction_id: notif.psp_reference, + payment_reference: notif.original_reference, + //Translating into custom status so that it can be clearly mapped to out attempt_status + status: match notif.event_code { + WebhookEventCode::Authorisation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Authorised } else { - AdyenStatus::Authorised + AdyenWebhookStatus::AuthorisationFailed } } - _ => AdyenStatus::Refused, + WebhookEventCode::Cancellation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Cancelled + } else { + AdyenWebhookStatus::CancelFailed + } + } + WebhookEventCode::Capture => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Captured + } else { + AdyenWebhookStatus::CaptureFailed + } + } + WebhookEventCode::CaptureFailed => AdyenWebhookStatus::CaptureFailed, + WebhookEventCode::CancelOrRefund + | WebhookEventCode::Refund + | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed + | WebhookEventCode::NotificationOfChargeback + | WebhookEventCode::Chargeback + | WebhookEventCode::ChargebackReversed + | WebhookEventCode::SecondChargeback + | WebhookEventCode::PrearbitrationWon + | WebhookEventCode::PrearbitrationLost + | WebhookEventCode::Unknown => AdyenWebhookStatus::UnexpectedEvent, }, amount: Some(Amount { value: notif.amount.value, currency: notif.amount.currency, }), + merchant_reference_id: notif.merchant_reference, refusal_reason: None, refusal_reason_code: None, - additional_data: None, - event_code: Some(notif.event_code), + event_code: notif.event_code, } } } -impl utils::MultipleCaptureSyncResponse for Response { +//This will be triggered in Psync handler of webhook response +impl utils::MultipleCaptureSyncResponse for AdyenWebhookResponse { fn get_connector_capture_id(&self) -> String { - self.psp_reference.clone() + self.transaction_id.clone() } fn get_capture_attempt_status(&self) -> enums::AttemptStatus { - match self.result_code { - AdyenStatus::Authorised => enums::AttemptStatus::Charged, + match self.status { + AdyenWebhookStatus::Captured => enums::AttemptStatus::Charged, _ => enums::AttemptStatus::CaptureFailed, } } fn is_capture_response(&self) -> bool { - self.event_code == Some(WebhookEventCode::Capture) - || self.event_code == Some(WebhookEventCode::CaptureFailed) + matches!( + self.event_code, + WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + ) } fn get_connector_reference_id(&self) -> Option<String> { - Some(self.merchant_reference.clone()) + Some(self.merchant_reference_id.clone()) } fn get_amount_captured(&self) -> Option<i64> {
2024-03-06T09:30:25Z
## Description <!-- Describe your changes in detail --> - Update Psync response handler to consume the incoming webhook response - Handle Webhook Status Mapping ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3977 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> For Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments. Payment Methods Need to be tested - Klarna (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Paypal (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Cards (Automatic and Manual) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - ideal (Automatic Capture) ``` **Confirm Call:** { "client_secret": "{{client_secret}}", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "billing_details": { "billing_name": "John Doe" }, "bank_name": "n26", "preferred_language": "en", "country": "NL" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` - Do any of the operation `REFUND, CANCEL, CAPTURE` - Wait for Configured webhooks - Do a sync for Success Scenario **Outgoing Webhooks Example** - Charged <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8"> </details> <details><summary> Ideal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144"> </details> - Authorized <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76"> </details> <details><summary> Cancelled </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86"> </details> <details><summary> Captured </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7"> </details> <details><summary> Refunded </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c"> </details>
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
For Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments. Payment Methods Need to be tested - Klarna (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Paypal (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Cards (Automatic and Manual) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - ideal (Automatic Capture) ``` **Confirm Call:** { "client_secret": "{{client_secret}}", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "billing_details": { "billing_name": "John Doe" }, "bank_name": "n26", "preferred_language": "en", "country": "NL" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` - Do any of the operation `REFUND, CANCEL, CAPTURE` - Wait for Configured webhooks - Do a sync for Success Scenario **Outgoing Webhooks Example** - Charged <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8"> </details> <details><summary> Ideal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144"> </details> - Authorized <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76"> </details> <details><summary> Cancelled </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86"> </details> <details><summary> Captured </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7"> </details> <details><summary> Refunded </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c"> </details>
[ "crates/router/src/connector/adyen.rs", "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-1464
Bug: [BUG] Adyen payment status update for Manual Capture payment ### Bug Description We have to rely on web hooks for status update for manual capture payment. But the problem is in both Auto And Manual capture flow we will receive `Authorized` event web hook, additionally in manual capture we will get one more event `Capture` which we have to rely for final status in manual capture flow. We will never have CaptureMethodType information during incoming web hooks to differentiate the flow during incoming web hooks ### Expected Behavior Adyen web hooks should be able to update status of all the payment methods irrespective of their capture method. ### Actual Behavior For Manual capture the payment status would be changed to success if we receive the `Authorized` status, But it should be updated only in `Capture` event ### Steps To Reproduce Create Manual capture payment for adyen connector, The final status should be updated only after `Capture` event ### Context For The Bug _No response_ ### Have you spent some time to check if this bug has been raised before? - [X] I checked and didn't find similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes I am willing to submit a PR!
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 93301364e62..67e319ddc22 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -403,6 +403,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentSession for Adyen {} @@ -516,6 +523,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } /// Payment Sync can be useful only incase of Redirect flow. @@ -681,6 +695,13 @@ impl ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> { Ok(services::CaptureSyncMethod::Individual) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -795,6 +816,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::PaymentsPreProcessing for Adyen {} @@ -925,6 +954,14 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl @@ -1022,6 +1059,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Payouts for Adyen {} @@ -1129,6 +1173,13 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1227,6 +1278,13 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1330,6 +1388,13 @@ impl ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } #[cfg(feature = "payouts")] @@ -1446,6 +1511,13 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl api::Refund for Adyen {} @@ -1553,6 +1625,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> @@ -1717,7 +1796,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - let response: adyen::Response = notif.into(); + let response = adyen::AdyenWebhookResponse::from(notif); Ok(Box::new(response)) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 9fbf7d99812..c44d590e2f1 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3,7 +3,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; use common_utils::{ext_traits::Encode, pii}; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -24,7 +24,7 @@ use crate::{ self, api::{self, enums as api_enums}, storage::enums as storage_enums, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, PaymentsAuthorizeData, }, utils as crate_utils, @@ -271,6 +271,31 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> } } +impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatus { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + (is_manual_capture, adyen_webhook_status): (bool, AdyenWebhookStatus), + ) -> Result<Self, Self::Error> { + match adyen_webhook_status { + AdyenWebhookStatus::Authorised => match is_manual_capture { + true => Ok(Self::Authorized), + // In case of Automatic capture Authorized is the final status of the payment + false => Ok(Self::Charged), + }, + AdyenWebhookStatus::AuthorisationFailed => Ok(Self::Failure), + AdyenWebhookStatus::Cancelled => Ok(Self::Voided), + AdyenWebhookStatus::CancelFailed => Ok(Self::VoidFailed), + AdyenWebhookStatus::Captured => Ok(Self::Charged), + AdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed), + //If Unexpected Event is received, need to understand how it reached this point + //Webhooks with Payment Events only should try to conume this resource object. + AdyenWebhookStatus::UnexpectedEvent => { + Err(errors::ConnectorError::WebhookBodyDecodingFailed).into_report() + } + } + } +} + #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AdyenRedirectRequest { pub details: AdyenRedirectRequestTypes, @@ -320,6 +345,7 @@ pub enum AdyenPaymentResponse { QrCodeResponse(Box<QrCodeResponseResponse>), RedirectionResponse(Box<RedirectionResponse>), RedirectionErrorResponse(Box<RedirectionErrorResponse>), + WebhookResponse(Box<AdyenWebhookResponse>), } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -332,8 +358,31 @@ pub struct Response { refusal_reason: Option<String>, refusal_reason_code: Option<String>, additional_data: Option<AdditionalData>, - // event_code will be available only in webhook body - event_code: Option<WebhookEventCode>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdyenWebhookStatus { + Authorised, + AuthorisationFailed, + Cancelled, + CancelFailed, + Captured, + CaptureFailed, + UnexpectedEvent, +} + +//Creating custom struct which can be consumed in Psync Handler triggered from Webhooks +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenWebhookResponse { + transaction_id: String, + payment_reference: Option<String>, + status: AdyenWebhookStatus, + amount: Option<Amount>, + merchant_reference_id: String, + refusal_reason: Option<String>, + refusal_reason_code: Option<String>, + event_code: WebhookEventCode, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3091,7 +3140,6 @@ pub fn get_adyen_response( > { let status = storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code, pmt)); - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { Some(types::ErrorResponse { code: response @@ -3135,10 +3183,11 @@ pub fn get_adyen_response( Ok((status, error, payments_response_data)) } -pub fn get_adyen_response_for_multiple_partial_capture( - response: Response, +pub fn get_webhook_response( + response: AdyenWebhookResponse, + is_capture_manual: bool, + is_multiple_capture_psync_flow: bool, status_code: u16, - pmt: Option<enums::PaymentMethodType>, ) -> errors::CustomResult< ( storage_enums::AttemptStatus, @@ -3147,28 +3196,53 @@ pub fn get_adyen_response_for_multiple_partial_capture( ), errors::ConnectorError, > { - let (status, error, _) = get_adyen_response(response.clone(), true, status_code, pmt)?; - let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); - let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); - Ok(( - status, - error, - types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - }, - )) -} + let status = storage_enums::AttemptStatus::foreign_try_from(( + is_capture_manual, + response.status.clone(), + ))?; + let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { + Some(types::ErrorResponse { + code: response + .refusal_reason_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response + .refusal_reason + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: response.refusal_reason.clone(), + status_code, + attempt_status: None, + connector_transaction_id: Some(response.transaction_id.clone()), + }) + } else { + None + }; -fn update_attempt_status_based_on_event_type_if_needed( - status: storage_enums::AttemptStatus, - event: &Option<WebhookEventCode>, -) -> storage_enums::AttemptStatus { - if status == storage_enums::AttemptStatus::Authorized - && event == &Some(WebhookEventCode::Capture) - { - storage_enums::AttemptStatus::Charged + if is_multiple_capture_psync_flow { + let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); + Ok(( + status, + error, + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + }, + )) } else { - status + let payments_response_data = types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response + .payment_reference + .unwrap_or(response.transaction_id), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.merchant_reference_id), + incremental_authorization_allowed: None, + }; + Ok((status, error, payments_response_data)) } } @@ -3656,11 +3730,7 @@ impl<F, Req> let is_manual_capture = utils::is_manual_capture(capture_method); let (status, error, payment_response_data) = match item.response { AdyenPaymentResponse::Response(response) => { - if is_multiple_capture_psync_flow { - get_adyen_response_for_multiple_partial_capture(*response, item.http_code, pmt)? - } else { - get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? - } + get_adyen_response(*response, is_manual_capture, item.http_code, pmt)? } AdyenPaymentResponse::PresentToShopper(response) => { get_present_to_shopper_response(*response, is_manual_capture, item.http_code, pmt)? @@ -3674,6 +3744,12 @@ impl<F, Req> AdyenPaymentResponse::RedirectionErrorResponse(response) => { get_redirection_error_response(*response, is_manual_capture, item.http_code, pmt)? } + AdyenPaymentResponse::WebhookResponse(response) => get_webhook_response( + *response, + is_manual_capture, + is_multiple_capture_psync_flow, + item.http_code, + )?, }; Ok(Self { @@ -3893,6 +3969,8 @@ pub enum WebhookEventCode { Refund, CancelOrRefund, Cancellation, + Capture, + CaptureFailed, RefundFailed, RefundReversed, NotificationOfChargeback, @@ -3901,8 +3979,6 @@ pub enum WebhookEventCode { SecondChargeback, PrearbitrationWon, PrearbitrationLost, - Capture, - CaptureFailed, #[serde(other)] Unknown, } @@ -4046,52 +4122,81 @@ pub struct AdyenIncomingWebhook { pub notification_items: Vec<AdyenItemObjectWH>, } -impl From<AdyenNotificationRequestItemWH> for Response { +impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse { fn from(notif: AdyenNotificationRequestItemWH) -> Self { Self { - psp_reference: notif.psp_reference, - merchant_reference: notif.merchant_reference, - result_code: match notif.success.as_str() { - "true" => { - if notif.event_code == WebhookEventCode::Cancellation { - AdyenStatus::Cancelled + transaction_id: notif.psp_reference, + payment_reference: notif.original_reference, + //Translating into custom status so that it can be clearly mapped to out attempt_status + status: match notif.event_code { + WebhookEventCode::Authorisation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Authorised } else { - AdyenStatus::Authorised + AdyenWebhookStatus::AuthorisationFailed } } - _ => AdyenStatus::Refused, + WebhookEventCode::Cancellation => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Cancelled + } else { + AdyenWebhookStatus::CancelFailed + } + } + WebhookEventCode::Capture => { + if is_success_scenario(notif.success) { + AdyenWebhookStatus::Captured + } else { + AdyenWebhookStatus::CaptureFailed + } + } + WebhookEventCode::CaptureFailed => AdyenWebhookStatus::CaptureFailed, + WebhookEventCode::CancelOrRefund + | WebhookEventCode::Refund + | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed + | WebhookEventCode::NotificationOfChargeback + | WebhookEventCode::Chargeback + | WebhookEventCode::ChargebackReversed + | WebhookEventCode::SecondChargeback + | WebhookEventCode::PrearbitrationWon + | WebhookEventCode::PrearbitrationLost + | WebhookEventCode::Unknown => AdyenWebhookStatus::UnexpectedEvent, }, amount: Some(Amount { value: notif.amount.value, currency: notif.amount.currency, }), + merchant_reference_id: notif.merchant_reference, refusal_reason: None, refusal_reason_code: None, - additional_data: None, - event_code: Some(notif.event_code), + event_code: notif.event_code, } } } -impl utils::MultipleCaptureSyncResponse for Response { +//This will be triggered in Psync handler of webhook response +impl utils::MultipleCaptureSyncResponse for AdyenWebhookResponse { fn get_connector_capture_id(&self) -> String { - self.psp_reference.clone() + self.transaction_id.clone() } fn get_capture_attempt_status(&self) -> enums::AttemptStatus { - match self.result_code { - AdyenStatus::Authorised => enums::AttemptStatus::Charged, + match self.status { + AdyenWebhookStatus::Captured => enums::AttemptStatus::Charged, _ => enums::AttemptStatus::CaptureFailed, } } fn is_capture_response(&self) -> bool { - self.event_code == Some(WebhookEventCode::Capture) - || self.event_code == Some(WebhookEventCode::CaptureFailed) + matches!( + self.event_code, + WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + ) } fn get_connector_reference_id(&self) -> Option<String> { - Some(self.merchant_reference.clone()) + Some(self.merchant_reference_id.clone()) } fn get_amount_captured(&self) -> Option<i64> {
2024-03-06T09:30:25Z
## Description <!-- Describe your changes in detail --> - Update Psync response handler to consume the incoming webhook response - Handle Webhook Status Mapping ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3977 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> For Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments. Payment Methods Need to be tested - Klarna (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Paypal (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Cards (Automatic and Manual) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - ideal (Automatic Capture) ``` **Confirm Call:** { "client_secret": "{{client_secret}}", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "billing_details": { "billing_name": "John Doe" }, "bank_name": "n26", "preferred_language": "en", "country": "NL" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` - Do any of the operation `REFUND, CANCEL, CAPTURE` - Wait for Configured webhooks - Do a sync for Success Scenario **Outgoing Webhooks Example** - Charged <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8"> </details> <details><summary> Ideal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144"> </details> - Authorized <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76"> </details> <details><summary> Cancelled </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86"> </details> <details><summary> Captured </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7"> </details> <details><summary> Refunded </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c"> </details>
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
For Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments. Payment Methods Need to be tested - Klarna (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "connector": [ "adyen" ], "payment_method_data": { "pay_later": { "klarna_redirect": { "billing_email": "hyperswitch_sdk_demo_id@gmail.com", "billing_country": "DE" } } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Paypal (Manual Capture) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Cards (Automatic and Manual) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "profile_id": "pro_doSItPZQZBbfoS0iEf81", "business_country": "US", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - ideal (Automatic Capture) ``` **Confirm Call:** { "client_secret": "{{client_secret}}", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "billing_details": { "billing_name": "John Doe" }, "bank_name": "n26", "preferred_language": "en", "country": "NL" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` - Do any of the operation `REFUND, CANCEL, CAPTURE` - Wait for Configured webhooks - Do a sync for Success Scenario **Outgoing Webhooks Example** - Charged <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8"> </details> <details><summary> Ideal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144"> </details> - Authorized <details><summary> Cards </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de"> </details> <details><summary> Paypal </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf"> </details> <details><summary> Klarna </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76"> </details> <details><summary> Cancelled </summary> <img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86"> </details> <details><summary> Captured </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7"> </details> <details><summary> Refunded </summary> <img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c"> </details>
[ "crates/router/src/connector/adyen.rs", "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3942
Bug: Set the PM as default if there is no Default PM for a customer
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..712b9a0edd7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -84,7 +84,8 @@ pub async fn create_payment_method( payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { - db.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) + let customer = db + .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; @@ -106,6 +107,17 @@ pub async fn create_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; + if customer.default_payment_method_id.is_none() { + let _ = set_default_payment_method( + db, + merchant_id.to_string(), + key_store.clone(), + customer_id, + payment_method_id.to_owned(), + ) + .await + .map_err(|err| logger::error!(error=?err,"Failed to set the payment method as default")); + } Ok(response) } @@ -3080,20 +3092,15 @@ async fn get_bank_account_connector_details( } } pub async fn set_default_payment_method( - state: routes::AppState, - merchant_account: domain::MerchantAccount, + db: &dyn db::StorageInterface, + merchant_id: String, key_store: domain::MerchantKeyStore, customer_id: &str, payment_method_id: String, ) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> { - let db = &*state.store; //check for the customer let customer = db - .find_customer_by_customer_id_merchant_id( - customer_id, - &merchant_account.merchant_id, - &key_store, - ) + .find_customer_by_customer_id_merchant_id(customer_id, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; // check for the presence of payment_method @@ -3103,8 +3110,7 @@ pub async fn set_default_payment_method( .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; utils::when( - payment_method.customer_id != customer_id - && payment_method.merchant_id != merchant_account.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(), @@ -3124,14 +3130,14 @@ pub async fn set_default_payment_method( )?; let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod { - default_payment_method_id: Some(payment_method_id.clone()), + default_payment_method_id: Some(payment_method_id.to_owned()), }; // update the db with the default payment method id let updated_customer_details = db .update_customer_by_customer_id_merchant_id( customer_id.to_owned(), - merchant_account.merchant_id, + merchant_id.to_owned(), customer_update, &key_store, ) diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1f793e2e185..baf395b230c 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -348,6 +348,7 @@ where } else { None }; + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( db, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 5469f981659..939cfaf93dc 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -275,15 +275,16 @@ pub async fn default_payment_method_set_api( Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; + let db = &*state.store.clone(); Box::pin(api::server_wrap( flow, state, &req, payload, - |state, auth: auth::AuthenticationData, default_payment_method| { + |_state, auth: auth::AuthenticationData, default_payment_method| { cards::set_default_payment_method( - state, - auth.merchant_account, + db, + auth.merchant_account.merchant_id, auth.key_store, &customer_id, default_payment_method.payment_method_id,
2024-03-05T19:07:00Z
## Description Set the initial payment method as default until its explicitly set ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create an MA and a MCA - Do a save card payment - Do a ListPaymentMethodsForCustomers the default flag would be set to true for the initial card - Do a save card payment, with other card , its default flag would be set to false, until explicitly set to true , using the endpoint `/customers/:customer_id/payment_methods/:payment_method_id/default` ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` <img width="1296" alt="Screenshot 2024-03-06 at 12 19 31 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/0fda5a3c-4f3a-4675-9b0c-b82958d28fe9">
1a8056799c7c2b486044b403fff2e74310c98c44
- Create an MA and a MCA - Do a save card payment - Do a ListPaymentMethodsForCustomers the default flag would be set to true for the initial card - Do a save card payment, with other card , its default flag would be set to false, until explicitly set to true , using the endpoint `/customers/:customer_id/payment_methods/:payment_method_id/default` ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` <img width="1296" alt="Screenshot 2024-03-06 at 12 19 31 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/0fda5a3c-4f3a-4675-9b0c-b82958d28fe9">
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/routes/payment_methods.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3957
Bug: Disallow deletion of default payment method for a customer Should not allow deletion of the default_payment_method of a customer. Error Message: "Cannot delete the default payment method" Merchant Error Handling: "Retry after setting another PM as default"
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index d28e988a039..c1f8b5e9c75 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -251,6 +251,8 @@ pub enum StripeErrorCode { InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] + PaymentMethodDeleteFailed, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes @@ -618,6 +620,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, + errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, } } } @@ -686,7 +689,8 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } - | Self::CurrencyConversionFailed => StatusCode::BAD_REQUEST, + | Self::CurrencyConversionFailed + | Self::PaymentMethodDeleteFailed => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index f9ed61e0f1b..46c90d776d4 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -252,6 +252,8 @@ pub enum ApiErrorResponse { InvalidConnectorConfiguration { config: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] + PaymentMethodDeleteFailed, } impl PTError for ApiErrorResponse { diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index ee63074544c..ce5253051e1 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -281,6 +281,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::CurrencyConversionFailed => { AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None)) } + Self::PaymentMethodDeleteFailed => { + AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None)) + } } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..7344cd09a5a 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3365,6 +3365,7 @@ pub async fn delete_payment_method( state: routes::AppState, merchant_account: domain::MerchantAccount, pm_id: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); let key = db @@ -3372,6 +3373,21 @@ pub async fn delete_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + let customer = db + .find_customer_by_customer_id_merchant_id( + &key.customer_id, + &merchant_account.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Customer not found for the payment method")?; + + utils::when( + customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id), + || Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed), + )?; + if key.payment_method == enums::PaymentMethod::Card { let response = delete_card_from_locker( &state, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 5469f981659..c0c79bde0cd 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -253,7 +253,9 @@ pub async fn payment_method_delete_api( state, &req, pm, - |state, auth, req| cards::delete_payment_method(state, auth.merchant_account, req), + |state, auth, req| { + cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ))
2024-03-05T11:43:51Z
## Description <!-- Describe your changes in detail --> If a payment method is set as a default payment method for a customer and it is tried to be deleted, we throw a invalid request error. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Store a card or any other payment method 2. Set that payment method as default ``` curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 3. Now try to delete that default payment method ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \ --header 'Accept: application/json' \ --header 'api-key: abc' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/840b23b2-ad0c-4af4-836e-11713537a220)
c65729adc9009f046398312a16841532fdc177da
1. Store a card or any other payment method 2. Set that payment method as default ``` curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 3. Now try to delete that default payment method ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \ --header 'Accept: application/json' \ --header 'api-key: abc' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/840b23b2-ad0c-4af4-836e-11713537a220)
[ "crates/router/src/compatibility/stripe/errors.rs", "crates/router/src/core/errors/api_error_response.rs", "crates/router/src/core/errors/transformers.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/routes/payment_methods.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3960
Bug: [FEATURE] Add USD Currency Filter for Bank Of America ### Feature Description The Bankofamerica connector needs to have a currency filter, restricting support exclusively to USD payments. ### Possible Implementation Config changes. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index dd05eb61d47..e9e80911e84 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -454,6 +454,12 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.stax] credit = { currency = "USD" } debit = { currency = "USD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index b7585f0c2ef..3ed64840b78 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -212,6 +212,12 @@ we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.braintree] paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index a105c4c0e94..382ad018f1d 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -226,6 +226,12 @@ we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.braintree] paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index ed718caa30d..396fd8b8628 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -227,6 +227,12 @@ pix = { country = "BR", currency = "BRL" } google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.braintree] paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" diff --git a/config/development.toml b/config/development.toml index 5d7366a89f3..c7bfefc3435 100644 --- a/config/development.toml +++ b/config/development.toml @@ -365,6 +365,12 @@ pay_easy = {country = "JP", currency = "JPY"} pix = { country = "BR", currency = "BRL" } boleto = { country = "BR", currency = "BRL" } +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.braintree] paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" } credit = { not_available_flows = { capture_method = "manual" } } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index f6de5ada7fa..892086a7b9f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -333,6 +333,12 @@ cashapp = {country = "US", currency = "USD"} [pm_filters.prophetpay] card_redirect = { currency = "USD" } +[pm_filters.bankofamerica] +credit = { currency = "USD" } +debit = { currency = "USD" } +apple_pay = { currency = "USD" } +google_pay = { currency = "USD" } + [pm_filters.helcim] credit = { currency = "USD" } debit = { currency = "USD" }
2024-03-05T10:20:49Z
## Description <!-- Describe your changes in detail --> The Bankofamerica connector now includes a currency filter, restricting support exclusively to USD payments. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables Following are the paths where you can find config files: 1. `config/development.toml` 2. `config/deployments/integration_test.toml` 3. `config/deployments/sandbox.toml` 4. `config/deployments/production.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3960 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payment Method List needs to be verified for USD and Non-USD payments via BOA: 1. Payments Request(with confirm false): ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "INR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "city": "תל אביב", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "business_label": "food", "business_country": "US" }' ``` Payments Response: ``` { "payment_id": "pay_3ftTdmvei4RVQamsfyfJ", "merchant_id": "merchant_1706697715", "status": "requires_payment_method", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2", "created": "2024-03-13T07:26:39.814Z", "currency": "INR", "customer_id": "CustomerX", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "תל אביב", "country": "US", "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1710314799, "expires": 1710318399, "secret": "epk_35a516b093434ef6a7bff36ae0efd437" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_j9PVFpZYzQU1j7yyjkJJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-13T07:41:39.813Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payment Methods List Request: ``` `curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'` ``` Payment Methods List Response: - For Non-USD Currencies: ``` { "redirect_url": "https://google.com/success", "currency": "INR", "payment_methods": [], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ``` - For USD: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
c65729adc9009f046398312a16841532fdc177da
Payment Method List needs to be verified for USD and Non-USD payments via BOA: 1. Payments Request(with confirm false): ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "INR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "city": "תל אביב", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "business_label": "food", "business_country": "US" }' ``` Payments Response: ``` { "payment_id": "pay_3ftTdmvei4RVQamsfyfJ", "merchant_id": "merchant_1706697715", "status": "requires_payment_method", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2", "created": "2024-03-13T07:26:39.814Z", "currency": "INR", "customer_id": "CustomerX", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "תל אביב", "country": "US", "line1": "eqnkl", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1710314799, "expires": 1710318399, "secret": "epk_35a516b093434ef6a7bff36ae0efd437" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_j9PVFpZYzQU1j7yyjkJJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-03-13T07:41:39.813Z", "fingerprint": null, "payment_method_id": null, "payment_method_status": null } ``` 2. Payment Methods List Request: ``` `curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'` ``` Payment Methods List Response: - For Non-USD Currencies: ``` { "redirect_url": "https://google.com/success", "currency": "INR", "payment_methods": [], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ``` - For USD: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "bankofamerica" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "bankofamerica" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.state": { "required_field": "billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "תל אביב" }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.last_name": { "required_field": "billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "ewcjwd" }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "46282" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "eqnkl" }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": "guest@example.com" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml" ]
juspay/hyperswitch
juspay__hyperswitch-3955
Bug: [BUG] [CI] NMI and Stripe CI failing As we can see here in CI's commit, https://github.com/juspay/hyperswitch/commit/cd7040fa8cad2e69a53e3ed609c9eb8a8a17495a, it is clear that NMI and Stripe collection are the ones that are affected which again can be confirmed with https://github.com/juspay/hyperswitch/actions/runs/8148897592/job/22272607599 CI checks are failing.
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index 006075895b5..ba0d2eb358b 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -18,17 +18,21 @@ fn main() { // Filter out None values leaving behind Some(Path) let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect(); - let git_status = Command::new("git").arg("restore").args(&paths).output(); - match git_status { - Ok(output) => { - if !output.status.success() { + if !paths.is_empty() { + let git_status = Command::new("git").arg("restore").args(&paths).output(); + + match git_status { + Ok(output) if !output.status.success() => { let stderr_str = String::from_utf8_lossy(&output.stderr); eprintln!("Git command failed with error: {stderr_str}"); } - } - Err(e) => { - eprintln!("Error running Git: {e}"); + Ok(_) => { + println!("Git restore successful!"); + } + Err(e) => { + eprintln!("Error running Git: {e}"); + } } } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 7b72495e5c4..9699acd8bb3 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 7b72495e5c4..9699acd8bb3 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json index bfeee020b5d..016af982e9e 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json @@ -30,6 +30,10 @@ "Scenario24-Add card flow", "Scenario25-Don't Pass CVV for save card flow and verifysuccess payment", "Scenario26-Save card payment with manual capture", - "Scenario27-Create payment without customer_id and with billing address and shipping address" + "Scenario27-Create payment without customer_id and with billing address and shipping address", + "Scenario28-Confirm a payment with requires_customer_action status", + "Scenario29-Create payment with payment method billing", + "Scenario30-Update payment with payment method billing", + "Scenario31-Pass payment method billing in Confirm" ] } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5a51941cf64..2b86201e2fe 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json index 3458081d489..89fd2e00d94 100644 --- a/postman/collection-json/nmi.postman_collection.json +++ b/postman/collection-json/nmi.postman_collection.json @@ -55,14 +55,7 @@ ], "request": { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": [ @@ -6842,7 +6835,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{another_random_number}}\"}" + "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id", @@ -6956,12 +6949,6 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, { "key": "publishable_key", "value": "", @@ -7315,7 +7302,7 @@ "language": "json" } }, - "raw": "{\"amount\":\"{{another_random_number}}\"}" + "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id", @@ -7429,12 +7416,6 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, { "key": "publishable_key", "value": "", diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 78a1777864a..e245b07fb97 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -55,14 +55,7 @@ ], "request": { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": [ @@ -6722,10 +6715,10 @@ ] }, { - "name": "Scenario28-Confirm a payment with requires_customer_action status", + "name": "Scenario1-Create payment with confirm true", "item": [ { - "name": "Payments - Create with confirm true", + "name": "Payments - Create", "event": [ { "listen": "test", @@ -6793,21 +6786,21 @@ " );", "}", "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have \"next_action.redirect_to_url\"", + "// Response body should have \"connector_transaction_id\"", "pm.test(", - " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",", + " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", " function () {", - " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be", + " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", " .true;", " },", ");", @@ -6836,7 +6829,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -6852,15 +6845,15 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 400\", function () {", - " pm.response.to.be.error;", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", @@ -6879,18 +6872,65 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) { }", + "} 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.\",", + " );", + "}", "", - "// Response body should have appropriatae error message", - "if (jsonData?.message) {", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"Succeeded\" for \"status\"", + "if (jsonData?.status) {", " pm.test(", - " \"Content check if appropriate error message is present\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.message).to.eql(\"You cannot confirm this payment because it has status requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", + "", + "// 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;", + " },", + ");", "" ], "type": "text/javascript" @@ -6898,55 +6938,27 @@ } ], "request": { - "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", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id", - "confirm" + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } ], "variable": [ { @@ -6956,14 +6968,14 @@ } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] } ] }, { - "name": "Scenario29-Create payment with payment method billing", + "name": "Scenario2a-Create payment with confirm false card holder name null", "item": [ { "name": "Payments - Create", @@ -6993,7 +7005,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) { }", + "} catch (e) {}", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -7034,33 +7046,24 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", - "", - "// 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;", - " },", - ");", - "", - "// Response body should have \"payment_method_data.billing\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", - " .true;", - " },", - ");", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -7086,7 +7089,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -7102,26 +7105,29 @@ "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -7129,7 +7135,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) { }", + "} catch (e) {}", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -7170,33 +7176,24 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// 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;", - " },", - ");", - "", - "// Response body should have \"payment_method_data.billing\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", - " .true;", - " },", - ");", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -7204,211 +7201,32 @@ } ], "request": { - "method": "GET", + "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": "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" - }, - "response": [] - } - ] - }, - { - "name": "Scenario30-Update payment with payment method billing", - "item": [ - { - "name": "Payments - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) { }", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set 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\");", - " },", - " );", - "}", - "" - ], - "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\":6540,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" - }, - "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 - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) { }", - "", - "// Response body should have value \"requires_confirmation\" 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_confirmation\");", - " },", - " );", - "}", - "", - "// Response body should have \"payment_method_data.billing\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", - " .true;", - " },", - ");", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" @@ -7421,25 +7239,27 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}}}" + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" + ":id", + "confirm" ], "variable": [ { "key": "id", - "value": "{{payment_id}}" + "value": "{{payment_id}}", + "description": "(Required) unique payment id" } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, @@ -7471,7 +7291,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) { }", + "} catch (e) {}", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -7512,24 +7332,15 @@ " );", "}", "", - "// Response body should have value \"requires_confirmation\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// Response body should have \"payment_method_data.billing\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", - " .true;", - " },", - ");", "" ], "type": "text/javascript" @@ -7574,7 +7385,7 @@ ] }, { - "name": "Scenario31-Pass payment method billing in Confirm", + "name": "Scenario2b-Create payment with confirm false card holder name empty", "item": [ { "name": "Payments - Create", @@ -7711,7 +7522,7 @@ "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", @@ -7783,8 +7594,7 @@ " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", - "}", - "" + "}" ], "type": "text/javascript" } @@ -7838,7 +7648,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -7890,7 +7700,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) { }", + "} catch (e) {}", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -7939,17 +7749,7 @@ " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", - "}", - "", - "// Response body should have \"payment_method_data.billing\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", - " .true;", - " },", - ");", - "" + "}" ], "type": "text/javascript" } @@ -7993,7 +7793,7 @@ ] }, { - "name": "Scenario1-Create payment with confirm true", + "name": "Scenario3-Create payment without PMD", "item": [ { "name": "Payments - Create", @@ -8064,24 +7864,144 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", + "" + ], + "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\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + }, + "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 - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", "", - "// Response body should have \"connector_transaction_id\"", + "// Validate if response header has matching content-type", "pm.test(", - " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", " function () {", - " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", - " .true;", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", " },", ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -8089,6 +8009,26 @@ } ], "request": { + "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": [ { @@ -8107,18 +8047,27 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, @@ -8191,24 +8140,15 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// 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;", - " },", - ");", "" ], "type": "text/javascript" @@ -8253,7 +8193,7 @@ ] }, { - "name": "Scenario2a-Create payment with confirm false card holder name null", + "name": "Scenario4-Create payment with Manual capture", "item": [ { "name": "Payments - Create", @@ -8324,12 +8264,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"requires_capture\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", " },", " );", "}", @@ -8337,15 +8277,6 @@ ], "type": "text/javascript" } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } } ], "request": { @@ -8367,7 +8298,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -8383,20 +8314,20 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Capture", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", "pm.test(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", " function () {", " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", " \"application/json\",", @@ -8405,7 +8336,7 @@ ");", "", "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -8457,21 +8388,32 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ + "", + "// 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 \"6000\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", + " function () {", + " pm.expect(jsonData.amount_received).to.eql(6540);", + " },", + " );", + "}", "" ], "type": "text/javascript" @@ -8479,26 +8421,6 @@ } ], "request": { - "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": [ { @@ -8517,17 +8439,17 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id/capture", "host": [ "{{baseUrl}}" ], "path": [ "payments", ":id", - "confirm" + "capture" ], "variable": [ { @@ -8537,7 +8459,7 @@ } ] }, - "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" + "description": "To capture the funds for an uncaptured payment" }, "response": [] }, @@ -8613,7 +8535,7 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", @@ -8663,7 +8585,7 @@ ] }, { - "name": "Scenario2b-Create payment with confirm false card holder name empty", + "name": "Scenario4a-Create payment with manual_multiple capture", "item": [ { "name": "Payments - Create", @@ -8734,12 +8656,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"requires_capture\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", " },", " );", "}", @@ -8747,15 +8669,6 @@ ], "type": "text/javascript" } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } } ], "request": { @@ -8777,7 +8690,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -8793,20 +8706,20 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Capture", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", "pm.test(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", " function () {", " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", " \"application/json\",", @@ -8815,7 +8728,7 @@ ");", "", "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -8867,20 +8780,32 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"partially_captured\");", " },", " );", - "}" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ + "}", + "", + "// 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 \"6000\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",", + " function () {", + " pm.expect(jsonData.amount_received).to.eql(6000);", + " },", + " );", + "}", "" ], "type": "text/javascript" @@ -8888,26 +8813,6 @@ } ], "request": { - "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": [ { @@ -8926,17 +8831,17 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id/capture", "host": [ "{{baseUrl}}" ], "path": [ "payments", ":id", - "confirm" + "capture" ], "variable": [ { @@ -8946,7 +8851,7 @@ } ] }, - "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" + "description": "To capture the funds for an uncaptured payment" }, "response": [] }, @@ -9022,12 +8927,13 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'partially_captured'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"partially_captured\");", " },", " );", - "}" + "}", + "" ], "type": "text/javascript" } @@ -9071,7 +8977,7 @@ ] }, { - "name": "Scenario3-Create payment without PMD", + "name": "Scenario5-Void the payment", "item": [ { "name": "Payments - Create", @@ -9142,12 +9048,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// Response body should have value \"requires_capture\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", " },", " );", "}", @@ -9176,7 +9082,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9192,20 +9098,20 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Cancel", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", "pm.test(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",", " function () {", " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", " \"application/json\",", @@ -9214,7 +9120,7 @@ ");", "", "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -9237,19 +9143,6 @@ " );", "}", "", - "// 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);", @@ -9262,12 +9155,13 @@ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", " );", "}", - "// Response body should have value \"succeeded\" for \"status\"", + "", + "// Response body should have value \"cancelled\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", " },", " );", "}", @@ -9275,38 +9169,9 @@ ], "type": "text/javascript" } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } } ], "request": { - "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": [ { @@ -9325,17 +9190,17 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id/cancel", "host": [ "{{baseUrl}}" ], "path": [ "payments", ":id", - "confirm" + "cancel" ], "variable": [ { @@ -9345,7 +9210,7 @@ } ] }, - "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" + "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" }, "response": [] }, @@ -9418,12 +9283,12 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"cancelled\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", " },", " );", "}", @@ -9471,7 +9336,7 @@ ] }, { - "name": "Scenario4-Create payment with Manual capture", + "name": "Scenario6-Create 3DS payment", "item": [ { "name": "Payments - Create", @@ -9542,15 +9407,24 @@ " );", "}", "", - "// Response body should have value \"requires_capture\" for \"status\"", + "// 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_capture'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " 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;", + " },", + ");", "" ], "type": "text/javascript" @@ -9576,7 +9450,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9592,29 +9466,26 @@ "response": [] }, { - "name": "Payments - Capture", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + "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(", - " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -9663,32 +9534,12 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_customer_action\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// 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 \"6000\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.amount_received).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", @@ -9699,137 +9550,10 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/capture", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To capture the funds for an uncaptured payment" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", + "key": "Accept", "value": "application/json" } ], @@ -9863,7 +9587,7 @@ ] }, { - "name": "Scenario4a-Create payment with manual_multiple capture", + "name": "Scenario7-Create 3DS payment with confrm false", "item": [ { "name": "Payments - Create", @@ -9934,12 +9658,12 @@ " );", "}", "", - "// Response body should have value \"requires_capture\" for \"status\"", + "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", " },", " );", "}", @@ -9968,7 +9692,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9984,20 +9708,20 @@ "response": [] }, { - "name": "Payments - Capture", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + "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/capture - Content-Type is application/json\",", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", " function () {", " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", " \"application/json\",", @@ -10006,7 +9730,7 @@ ");", "", "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -10055,35 +9779,33 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_customer_action\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"partially_captured\");", - " },", - " );", - "}", - "", - "// 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'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", "", - "// Response body should have value \"6000\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",", - " function () {", - " pm.expect(jsonData.amount_received).to.eql(6000);", - " },", - " );", - "}", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if 'next_action.redirect_to_url' exists\",", + " function () {", + " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be", + " .true;", + " },", + ");", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -10091,6 +9813,26 @@ } ], "request": { + "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": [ { @@ -10109,17 +9851,17 @@ "language": "json" } }, - "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + "raw": "{\"client_secret\":\"{{client_secret}}\"}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/capture", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", ":id", - "capture" + "confirm" ], "variable": [ { @@ -10129,7 +9871,7 @@ } ] }, - "description": "To capture the funds for an uncaptured payment" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, @@ -10202,12 +9944,12 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_customer_action\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'partially_captured'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"partially_captured\");", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", @@ -10255,7 +9997,7 @@ ] }, { - "name": "Scenario5-Void the payment", + "name": "Scenario8-Create a failure card payment with confirm true", "item": [ { "name": "Payments - Create", @@ -10326,120 +10068,41 @@ " );", "}", "", - "// Response body should have value \"requires_capture\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " pm.expect(jsonData.status).to.eql(\"failed\");", " },", " );", "}", - "" - ], - "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\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "Payments - Cancel", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", "", - "// Validate if response header has matching content-type", + "// Response body should have \"connector_transaction_id\"", "pm.test(", - " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",", + " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", + " .true;", " },", ");", "", - "// Validate if response has JSON Body", - "pm.test(\"[POST]::/payments/:id/cancel - 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 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 \"card_declined\" for \"error_code\"", + "if (jsonData?.error_code) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",", + " function () {", + " pm.expect(jsonData.error_code).to.eql(\"card_declined\");", + " },", " );", "}", "", - "// Response body should have value \"cancelled\" for \"status\"", - "if (jsonData?.status) {", + "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"", + "if (jsonData?.error_message) {", " pm.test(", - " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"cancelled\");", + " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");", " },", " );", "}", @@ -10468,27 +10131,18 @@ "language": "json" } }, - "raw": "{\"cancellation_reason\":\"requested_by_customer\"}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action" + "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": [] }, @@ -10561,12 +10215,41 @@ " );", "}", "", - "// Response body should have value \"cancelled\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"cancelled\");", + " pm.expect(jsonData.status).to.eql(\"failed\");", + " },", + " );", + "}", + "", + "// 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;", + " },", + ");", + "", + "// Response body should have value \"card_declined\" for \"error_code\"", + "if (jsonData?.error_code) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",", + " function () {", + " pm.expect(jsonData.error_code).to.eql(\"card_declined\");", + " },", + " );", + "}", + "", + "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"", + "if (jsonData?.error_message) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",", + " function () {", + " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");", " },", " );", "}", @@ -10614,7 +10297,7 @@ ] }, { - "name": "Scenario6-Create 3DS payment", + "name": "Scenario9-Refund full payment", "item": [ { "name": "Payments - Create", @@ -10685,24 +10368,15 @@ " );", "}", "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// 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;", - " },", - ");", "" ], "type": "text/javascript" @@ -10728,7 +10402,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -10812,12 +10486,12 @@ " );", "}", "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", @@ -10861,87 +10535,61 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario7-Create 3DS payment with confrm false", - "item": [ + }, { - "name": "Payments - Create", + "name": "Refunds - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/refunds - 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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"requires_confirmation\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " pm.expect(jsonData.amount).to.eql(6540);", " },", " );", "}", @@ -10970,46 +10618,38 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds" ] }, - "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" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Confirm", + "name": "Refunds - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "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(", - " \"[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();", + "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", @@ -11018,216 +10658,35 @@ " 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);", + "// 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 {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if 'next_action.redirect_to_url' exists\",", - " function () {", - " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be", - " .true;", - " },", - ");", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "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": "{\"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" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(", - " \"- use {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", - " );", - "}", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.amount).to.eql(6540);", " },", " );", "}", @@ -11246,36 +10705,30 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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": "Scenario8-Create a failure card payment with confirm true", + "name": "Scenario9a-Partial refund", "item": [ { "name": "Payments - Create", @@ -11349,38 +10802,9 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"failed\");", - " },", - " );", - "}", - "", - "// 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;", - " },", - ");", - "", - "// Response body should have value \"card_declined\" for \"error_code\"", - "if (jsonData?.error_code) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",", - " function () {", - " pm.expect(jsonData.error_code).to.eql(\"card_declined\");", - " },", - " );", - "}", - "", - "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"", - "if (jsonData?.error_message) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", @@ -11409,7 +10833,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -11496,38 +10920,9 @@ "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"failed\");", - " },", - " );", - "}", - "", - "// 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;", - " },", - ");", - "", - "// Response body should have value \"card_declined\" for \"error_code\"", - "if (jsonData?.error_code) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",", - " function () {", - " pm.expect(jsonData.error_code).to.eql(\"card_declined\");", - " },", - " );", - "}", - "", - "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"", - "if (jsonData?.error_message) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", @@ -11571,87 +10966,61 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario9-Refund full payment", - "item": [ + }, { - "name": "Payments - Create", + "name": "Refunds - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/refunds - 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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.amount).to.eql(540);", " },", " );", "}", @@ -11680,96 +11049,75 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds" ] }, - "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" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Refunds - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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]::/payments/:id - Content-Type is application/json\", function () {", + "pm.test(\"[GET]::/refunds/: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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.amount).to.eql(540);", " },", " );", "}", @@ -11788,34 +11136,28 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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", + "name": "Refunds - Create-copy", "event": [ { "listen": "test", @@ -11862,12 +11204,12 @@ " );", "}", "", - "// Response body should have value \"6540\" for \"amount\"", + "// Response body should have value \"1000\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(6540);", + " pm.expect(jsonData.amount).to.eql(1000);", " },", " );", "}", @@ -11896,7 +11238,7 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/refunds", @@ -11912,7 +11254,7 @@ "response": [] }, { - "name": "Refunds - Retrieve", + "name": "Refunds - Retrieve-copy", "event": [ { "listen": "test", @@ -11962,9 +11304,9 @@ "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(6540);", + " pm.expect(jsonData.amount).to.eql(1000);", " },", " );", "}", @@ -12002,33 +11344,28 @@ "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": "Scenario9a-Partial refund", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Retrieve-copy", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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(\"[POST]::/payments - Content-Type is application/json\", function () {", + "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(\"[POST]::/payments - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -12077,15 +11414,20 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", + "", + "// Response body should have \"refunds\"", + "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {", + " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;", + "});", "" ], "type": "text/javascript" @@ -12093,60 +11435,66 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario10-Create a mandate and recurring payment", + "item": [ { - "name": "Payments - Retrieve", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -12195,113 +11543,41 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "" - ], - "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 payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "response": [] - }, - { - "name": "Refunds - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", - "", - "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", - " console.log(", - " \"- use {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", "", "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have value \"540\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(540);", - " },", - " );", - "}", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -12327,78 +11603,115 @@ "language": "json" } }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments" ] }, - "description": "To create a refund against an already processed payment" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "Refunds - Retrieve", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + "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]::/refunds/:id - Content-Type is application/json\", function () {", + "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 refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + "// 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.\",", " );", "}", "", - "// Response body should have value \"6540\" for \"amount\"", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(540);", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", + "", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -12414,180 +11727,134 @@ } ], "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] }, { - "name": "Refunds - Create-copy", + "name": "Recurring Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + "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]::/refunds - Content-Type is application/json\", function () {", + "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 refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"1000\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(1000);", - " },", + "// 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,", " );", - "}", - "" - ], - "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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve-copy", - "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\",", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", " );", - "});", - "", - "// 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);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", " );", "}", "", "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have value \"6540\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(1000);", - " },", - " );", - "}", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"payment_method_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -12595,31 +11862,36 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + }, "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } + "payments" ] }, - "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" + "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": [] }, @@ -12702,10 +11974,21 @@ " );", "}", "", - "// Response body should have \"refunds\"", - "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {", - " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;", - "});", + "// Response body should have \"mandate_id\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have \"mandate_data\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'mandate_data' exists\",", + " function () {", + " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", + " },", + ");", "" ], "type": "text/javascript" @@ -12750,7 +12033,7 @@ ] }, { - "name": "Scenario10-Create a mandate and recurring payment", + "name": "Scenario11-Refund recurring payment", "item": [ { "name": "Payments - Create", @@ -12881,7 +12164,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -13110,6 +12393,16 @@ " );", "}", "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", "// Response body should have \"mandate_id\"", "pm.test(", " \"[POST]::/payments - Content check if 'mandate_id' exists\",", @@ -13158,7 +12451,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -13307,116 +12600,64 @@ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - } - ] - }, - { - "name": "Scenario11-Refund recurring payment", - "item": [ + }, { - "name": "Payments - Create", + "name": "Refunds - Create Copy", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/refunds - 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);", + "// 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 {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.amount).to.eql(6540);", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -13442,115 +12683,78 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds" ] }, - "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" + "description": "To create a refund against an already processed payment" }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Refunds - Retrieve Copy", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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]::/payments/:id - Content-Type is application/json\", function () {", + "pm.test(\"[GET]::/refunds/: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);", + "// 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 {{mandate_id}} as collection variable for value\",", - " jsonData.mandate_id,", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", " );", "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(", - " \"- use {{client_secret}} as collection variable for value\",", - " jsonData.client_secret,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"6540\" for \"amount\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.amount).to.eql(6540);", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -13566,34 +12770,33 @@ } ], "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments", + "refunds", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{refund_id}}", + "description": "(Required) unique refund 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" + "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": "Scenario12-BNPL-klarna", + "item": [ { - "name": "Recurring Payments - Create", + "name": "Payments - Create", "event": [ { "listen": "test", @@ -13661,49 +12864,15 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", - "", - "// Response body should have \"mandate_id\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have \"payment_method_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'payment_method_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;", - " },", - ");", "" ], "type": "text/javascript" @@ -13729,7 +12898,7 @@ "language": "json" } }, - "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":8000,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -13745,26 +12914,29 @@ "response": [] }, { - "name": "Payments - Retrieve-copy", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "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(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -13813,31 +12985,53 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// 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 'succeeded'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", "", - "// Response body should have \"mandate_id\"", + "// Response body should have \"next_action.redirect_to_url\"", "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_id' exists\",", + " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",", " function () {", - " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;", + " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be", + " .true;", " },", ");", "", - "// Response body should have \"mandate_data\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'mandate_data' exists\",", - " function () {", - " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;", - " },", - ");", + "// Response body should have value \"klarna\" for \"payment_method_type\"", + "if (jsonData?.payment_method_type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'klarna'\",", + " function () {", + " pm.expect(jsonData.payment_method_type).to.eql(\"klarna\");", + " },", + " );", + "}", + "", + "// Response body should have value \"stripe\" for \"connector\"", + "if (jsonData?.connector) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", + " function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -13845,27 +13039,55 @@ } ], "request": { - "method": "GET", + "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": "Accept", + "key": "Content-Type", "value": "application/json" - } + }, + { + "key": "Accept", + "value": "application/json" + } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"klarna_redirect\":{\"issuer_name\":\"stripe\",\"billing_email\":\"arjun.karthik@juspay.in\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } + ":id", + "confirm" ], "variable": [ { @@ -13875,161 +13097,85 @@ } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "Refunds - Create Copy", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + "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(\"[POST]::/refunds - Content-Type is application/json\", function () {", + "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 refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + "// 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,", " );", - "}", - "", - "// Response body should have value \"6540\" for \"amount\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", - " function () {", - " pm.expect(jsonData.amount).to.eql(6540);", - " },", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", " );", "}", - "" - ], - "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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" - }, - "response": [] - }, - { - "name": "Refunds - Retrieve Copy", - "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);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", - " );", - "}", - "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", " );", "}", "", - "// Response body should have value \"6540\" for \"amount\"", + "// Response body should have value \"requires_customer_action\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", @@ -14048,30 +13194,36 @@ } ], "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", + "payments", ":id" ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], "variable": [ { "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] } ] }, { - "name": "Scenario12-BNPL-klarna", + "name": "Scenario13-BNPL-afterpay", "item": [ { "name": "Payments - Create", @@ -14176,7 +13328,7 @@ "language": "json" } }, - "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":8000,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -14282,12 +13434,12 @@ " },", ");", "", - "// Response body should have value \"klarna\" for \"payment_method_type\"", + "// Response body should have value \"afterpay_clearpay\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'klarna'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'afterpay_clearpay'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"klarna\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");", " },", " );", "}", @@ -14355,7 +13507,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"klarna_redirect\":{\"issuer_name\":\"stripe\",\"billing_email\":\"arjun.karthik@juspay.in\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"afterpay_clearpay_redirect\":{\"billing_name\":\"Akshaya\",\"billing_email\":\"example@example.com\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -14501,7 +13653,7 @@ ] }, { - "name": "Scenario13-BNPL-afterpay", + "name": "Scenario14-BNPL-affirm", "item": [ { "name": "Payments - Create", @@ -14606,7 +13758,7 @@ "language": "json" } }, - "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -14712,12 +13864,12 @@ " },", ");", "", - "// Response body should have value \"afterpay_clearpay\" for \"payment_method_type\"", + "// Response body should have value \"affirm\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'afterpay_clearpay'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'affirm'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");", " },", " );", "}", @@ -14785,7 +13937,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"afterpay_clearpay_redirect\":{\"billing_name\":\"Akshaya\",\"billing_email\":\"example@example.com\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"affirm_redirect\":{\"issuer_name\":\"affirm\",\"billing_email\":\"user-us@example.com\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -14931,7 +14083,7 @@ ] }, { - "name": "Scenario14-BNPL-affirm", + "name": "Scenario15-Bank Redirect-Ideal", "item": [ { "name": "Payments - Create", @@ -15036,7 +14188,7 @@ "language": "json" } }, - "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15142,12 +14294,12 @@ " },", ");", "", - "// Response body should have value \"affirm\" for \"payment_method_type\"", + "// Response body should have value \"ideal\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'affirm'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ideal'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");", " },", " );", "}", @@ -15215,7 +14367,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"affirm_redirect\":{\"issuer_name\":\"affirm\",\"billing_email\":\"user-us@example.com\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"ing\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -15361,7 +14513,7 @@ ] }, { - "name": "Scenario15-Bank Redirect-Ideal", + "name": "Scenario16-Bank Redirect-sofort", "item": [ { "name": "Payments - Create", @@ -15572,12 +14724,12 @@ " },", ");", "", - "// Response body should have value \"ideal\" for \"payment_method_type\"", + "// Response body should have value \"sofort\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ideal'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'sofort'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");", " },", " );", "}", @@ -15645,7 +14797,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"ing\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"sofort\",\"payment_method_data\":{\"bank_redirect\":{\"sofort\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_noe_lb_fur_niederosterreich_u_wien\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -15791,7 +14943,7 @@ ] }, { - "name": "Scenario16-Bank Redirect-sofort", + "name": "Scenario17-Bank Redirect-eps", "item": [ { "name": "Payments - Create", @@ -16002,12 +15154,12 @@ " },", ");", "", - "// Response body should have value \"sofort\" for \"payment_method_type\"", + "// Response body should have value \"eps\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'sofort'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'eps'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");", " },", " );", "}", @@ -16075,7 +15227,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"sofort\",\"payment_method_data\":{\"bank_redirect\":{\"sofort\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_noe_lb_fur_niederosterreich_u_wien\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -16221,7 +15373,7 @@ ] }, { - "name": "Scenario17-Bank Redirect-eps", + "name": "Scenario18-Bank Redirect-giropay", "item": [ { "name": "Payments - Create", @@ -16432,12 +15584,12 @@ " },", ");", "", - "// Response body should have value \"eps\" for \"payment_method_type\"", + "// Response body should have value \"giropay\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'eps'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'giropay'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");", " },", " );", "}", @@ -16505,7 +15657,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"giropay\",\"payment_method_data\":{\"bank_redirect\":{\"giropay\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -16651,7 +15803,7 @@ ] }, { - "name": "Scenario18-Bank Redirect-giropay", + "name": "Scenario19-Bank Transfer-ach", "item": [ { "name": "Payments - Create", @@ -16756,7 +15908,7 @@ "language": "json" } }, - "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -16853,21 +16005,32 @@ " );", "}", "", - "// Response body should have \"next_action.redirect_to_url\"", + "// Response body should have \"next_action.type\"", "pm.test(", - " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",", + " \"[POST]::/payments - Content check if 'next_action.type' exists\",", " function () {", - " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be", - " .true;", + " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;", " },", ");", "", - "// Response body should have value \"giropay\" for \"payment_method_type\"", + "// Response body should have value \"ach\" for \"payment_method_type\"", "if (jsonData?.payment_method_type) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'giropay'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ach'\",", " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");", + " pm.expect(jsonData.payment_method_type).to.eql(\"ach\");", + " },", + " );", + "}", + "", + "// Response body should have value \"display_bank_transfer_information\" for \"next_action.type\"", + "if (jsonData?.next_action.type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'display_bank_transfer_information'\",", + " function () {", + " pm.expect(jsonData.next_action.type).to.eql(", + " \"display_bank_transfer_information\",", + " );", " },", " );", "}", @@ -16935,7 +16098,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"giropay\",\"payment_method_data\":{\"bank_redirect\":{\"giropay\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_transfer\":{\"ach_bank_transfer\":{\"billing_details\":{\"email\":\"johndoe@example.com\"}}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", @@ -17081,7 +16244,7 @@ ] }, { - "name": "Scenario19-Bank Transfer-ach", + "name": "Scenario20-Bank Debit-ach", "item": [ { "name": "Payments - Create", @@ -17152,12 +16315,12 @@ " );", "}", "", - "// Response body should have value \"requires_payment_method\" for \"status\"", + "// 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_payment_method'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", @@ -17165,6 +16328,15 @@ ], "type": "text/javascript" } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } } ], "request": { @@ -17186,7 +16358,7 @@ "language": "json" } }, - "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":1800,\"currency\":\"USD\",\"confirm\":true,\"business_label\":\"default\",\"capture_method\":\"automatic\",\"connector\":[\"stripe\"],\"customer_id\":\"klarna\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"authentication_type\":\"three_ds\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"return_url\":\"https://google.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"setup_future_usage\":\"off_session\",\"business_country\":\"US\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"mandate_type\":{\"single_use\":{\"amount\":6540,\"currency\":\"USD\"}}},\"payment_method\":\"bank_debit\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -17202,29 +16374,26 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "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(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -17276,61 +16445,12 @@ "// 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'\",", + " \"[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 \"next_action.type\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'next_action.type' exists\",", - " function () {", - " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have value \"ach\" for \"payment_method_type\"", - "if (jsonData?.payment_method_type) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ach'\",", - " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"ach\");", - " },", - " );", - "}", - "", - "// Response body should have value \"display_bank_transfer_information\" for \"next_action.type\"", - "if (jsonData?.next_action.type) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'display_bank_transfer_information'\",", - " function () {", - " pm.expect(jsonData.next_action.type).to.eql(", - " \"display_bank_transfer_information\",", - " );", - " },", - " );", - "}", - "", - "// Response body should have value \"stripe\" for \"connector\"", - "if (jsonData?.connector) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", - " function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - " },", - " );", - "}", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ "" ], "type": "text/javascript" @@ -17338,55 +16458,27 @@ } ], "request": { - "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", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_transfer\":{\"ach_bank_transfer\":{\"billing_details\":{\"email\":\"johndoe@example.com\"}}}},\"client_secret\":\"{{client_secret}}\"}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id", - "confirm" + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } ], "variable": [ { @@ -17396,31 +16488,36 @@ } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario21-Wallet-Wechatpay", + "item": [ { - "name": "Payments - Retrieve", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -17469,12 +16566,12 @@ " );", "}", "", - "// Response body should have value \"requires_customer_action\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", @@ -17485,66 +16582,63 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "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": "Scenario20-Bank Debit-ach", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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 - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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 - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -17596,28 +16690,86 @@ "// 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'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], + "", + "// Response body should have \"next_action.type\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'next_action.type' exists\",", + " function () {", + " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;", + " },", + ");", + "", + "// Response body should have value \"ach\" for \"payment_method_type\"", + "if (jsonData?.payment_method_type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'we_chat_pay'\",", + " function () {", + " pm.expect(jsonData.payment_method_type).to.eql(\"we_chat_pay\");", + " },", + " );", + "}", + "", + "// Response body should have value \"qr_code_information\" for \"next_action.type\"", + "if (jsonData?.next_action.type) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'qr_code_information'\",", + " function () {", + " pm.expect(jsonData.next_action.type).to.eql(\"qr_code_information\");", + " },", + " );", + "}", + "", + "// Response body should have value \"stripe\" for \"connector\"", + "if (jsonData?.connector) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", + " function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], "type": "text/javascript" } } ], "request": { + "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": [ { @@ -17636,18 +16788,27 @@ "language": "json" } }, - "raw": "{\"amount\":1800,\"currency\":\"USD\",\"confirm\":true,\"business_label\":\"default\",\"capture_method\":\"automatic\",\"connector\":[\"stripe\"],\"customer_id\":\"klarna\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"authentication_type\":\"three_ds\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"return_url\":\"https://google.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"setup_future_usage\":\"off_session\",\"business_country\":\"US\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"mandate_type\":{\"single_use\":{\"amount\":6540,\"currency\":\"USD\"}}},\"payment_method\":\"bank_debit\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, @@ -17773,7 +16934,7 @@ ] }, { - "name": "Scenario21-Wallet-Wechatpay", + "name": "Scenario22- Update address and List Payment method", "item": [ { "name": "Payments - Create", @@ -17782,77 +16943,62 @@ "listen": "test", "script": { "exec": [ - "// Validate status 2xx", + "// Validate status 2xx ", "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\",", - " );", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", "});", "", - "// Validate if response has JSON Body", + "// Validate if response has JSON Body ", "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", + "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,", - " );", + " 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.\",", - " );", - "}", + " 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,", - " );", + " 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.\",", - " );", - "}", + " 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,", - " );", + " 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.\",", - " );", - "}", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", "", + "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};", "// 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\");", - " },", - " );", - "}", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", + "})};", "" ], "type": "text/javascript" @@ -17878,7 +17024,7 @@ "language": "json" } }, - "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -17894,134 +17040,63 @@ "response": [] }, { - "name": "Payments - Confirm", + "name": "List Payment Methods for a Merchant", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 2xx ", + "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(", - " \"[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();", + "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", "});", "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", + "// Parse the response body as JSON", + "var responseBody = pm.response.json();", "", - "// 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.\",", - " );", - "}", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"card\";", + " });", + "});", "", - "// 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.\",", - " );", - "}", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"pay_later\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'pay_later'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"pay_later\";", + " });", + "});", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"wallet\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'wallet'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"wallet\";", + " });", + "});", "", - "// 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.\",", - " );", - "}", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_debit\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_debit'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"bank_debit\";", + " });", + "});", "", - "// 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.type\"", - "pm.test(", - " \"[POST]::/payments - Content check if 'next_action.type' exists\",", - " function () {", - " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;", - " },", - ");", - "", - "// Response body should have value \"ach\" for \"payment_method_type\"", - "if (jsonData?.payment_method_type) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'we_chat_pay'\",", - " function () {", - " pm.expect(jsonData.payment_method_type).to.eql(\"we_chat_pay\");", - " },", - " );", - "}", - "", - "// Response body should have value \"qr_code_information\" for \"next_action.type\"", - "if (jsonData?.next_action.type) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'qr_code_information'\",", - " function () {", - " pm.expect(jsonData.next_action.type).to.eql(\"qr_code_information\");", - " },", - " );", - "}", - "", - "// Response body should have value \"stripe\" for \"connector\"", - "if (jsonData?.connector) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", - " function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - " },", - " );", - "}", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_transfer\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_transfer'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"bank_transfer\";", + " });", + "});" ], "type": "text/javascript" } @@ -18048,126 +17123,78 @@ } ] }, - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}},\"client_secret\":\"{{client_secret}}\"}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" + "account", + "payment_methods" ], - "variable": [ + "query": [ { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "key": "client_secret", + "value": "{{client_secret}}" } ] }, - "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" + "description": "To filter and list the applicable payment methods for a particular merchant id." }, "response": [] }, { - "name": "Payments - Retrieve", + "name": "Payments - Update", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", + "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", "});", "", - "// Validate if response has JSON Body", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", "});", "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {", - " jsonData = pm.response.json();", - "} catch (e) {}", "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(", - " \"- use {{payment_id}} as collection variable for value\",", - " jsonData.payment_id,", - " );", - "} else {", - " console.log(", - " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", - " );", - "}", + "// Parse the JSON response", + "var jsonData = pm.response.json();", "", - "// 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.\",", - " );", - "}", + "// Check if the 'currency' is equal to \"EUR\"", + "pm.test(\"[POST]::/payments/:id -Content Check if 'currency' matches 'EUR' \", function () {", + " pm.expect(jsonData.currency).to.eql(\"EUR\");", + "});", "", - "// 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.\",", - " );", - "}", + "// Extract the \"country\" field from the JSON data", + "var country = jsonData.billing.address.country;", "", - "// 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\");", - " },", - " );", - "}", + "// Check if the country is \"NL\"", + "pm.test(\"[POST]::/payments/:id -Content Check if billing 'Country' matches NL (Netherlands)\", function () {", + " pm.expect(country).to.equal(\"NL\");", + "});", + "", + "var country1 = jsonData.shipping.address.country;", + "", + "// Check if the country is \"NL\"", + "pm.test(\"[POST]::/payments/:id -Content Check if shipping 'Country' matches NL (Netherlands)\", function () {", + " pm.expect(country1).to.equal(\"NL\");", + "});", "" ], "type": "text/javascript" @@ -18175,15 +17202,28 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"currency\":\"EUR\",\"shipping\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}},\"billing\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id", "host": [ "{{baseUrl}}" ], @@ -18191,188 +17231,59 @@ "payments", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{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" + "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " }, "response": [] - } - ] - }, - { - "name": "Scenario22- Update address and List Payment method", - "item": [ + }, { - "name": "Payments - Create", + "name": "List Payment Methods for a Merchant-copy", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", " pm.response.to.be.success;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", "});", "", - "// 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){}", + "// Parse the response body as JSON", + "var responseBody = pm.response.json();", "", - "// 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.');", - "};", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"card\";", + " });", + "});", "", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"ideal\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id - Content Check if payment_method matches 'ideal'\", function () {", + " var paymentMethods = responseBody.payment_methods;", + " var cardPaymentMethod = paymentMethods.find(function (method) {", + " return method.payment_method == \"ideal\";", + " });", + "});", "", - "// 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.');", - "};", - "", - "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", - "// 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\");", - "})};", - "" - ], - "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\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" - }, - "response": [] - }, - { - "name": "List Payment Methods for a Merchant", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Parse the response body as JSON", - "var responseBody = pm.response.json();", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"card\";", - " });", - "});", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"pay_later\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'pay_later'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"pay_later\";", - " });", - "});", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"wallet\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'wallet'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"wallet\";", - " });", - "});", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_debit\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_debit'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"bank_debit\";", - " });", - "});", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_transfer\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_transfer'\", function () {", + "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_redirect\"", + "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_redirect'\", function () {", " var paymentMethods = responseBody.payment_methods;", " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"bank_transfer\";", + " return method.payment_method == \"bank_redirect\";", " });", "});" ], @@ -18406,12 +17317,6 @@ { "key": "Accept", "value": "application/json" - }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true } ], "url": { @@ -18435,50 +17340,37 @@ "response": [] }, { - "name": "Payments - Update", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {", + "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 - Content-Type is application/json\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - 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(\"[POST]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", + "//// 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\");", + "})};", "", - "// Parse the JSON response", - "var jsonData = pm.response.json();", - "", - "// Check if the 'currency' is equal to \"EUR\"", - "pm.test(\"[POST]::/payments/:id -Content Check if 'currency' matches 'EUR' \", function () {", - " pm.expect(jsonData.currency).to.eql(\"EUR\");", - "});", - "", - "// Extract the \"country\" field from the JSON data", - "var country = jsonData.billing.address.country;", - "", - "// Check if the country is \"NL\"", - "pm.test(\"[POST]::/payments/:id -Content Check if billing 'Country' matches NL (Netherlands)\", function () {", - " pm.expect(country).to.equal(\"NL\");", - "});", - "", - "var country1 = jsonData.shipping.address.country;", - "", - "// Check if the country is \"NL\"", - "pm.test(\"[POST]::/payments/:id -Content Check if shipping 'Country' matches NL (Netherlands)\", function () {", - " pm.expect(country1).to.equal(\"NL\");", - "});", "" ], "type": "text/javascript" @@ -18486,6 +17378,26 @@ } ], "request": { + "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": [ { @@ -18504,16 +17416,17 @@ "language": "json" } }, - "raw": "{\"currency\":\"EUR\",\"shipping\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}},\"billing\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}}}" + "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\",\"email\":\"guest@example.com\"},\"bank_name\":\"ing\"}}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"125.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":7000,\"currency\":\"USD\",\"start_date\":\"2023-04-21T00:00:00Z\",\"end_date\":\"2023-05-21T00:00:00Z\",\"metadata\":{\"frequency\":\"13\"}}}},\"setup_future_usage\":\"off_session\",\"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\":\"128.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id" + ":id", + "confirm" ], "variable": [ { @@ -18522,246 +17435,43 @@ } ] }, - "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created " + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, { - "name": "List Payment Methods for a Merchant-copy", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {", + "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]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {", + "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();", + "});", "", - "// Parse the response body as JSON", - "var responseBody = pm.response.json();", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"card\";", - " });", - "});", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"ideal\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id - Content Check if payment_method matches 'ideal'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"ideal\";", - " });", - "});", - "", - "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_redirect\"", - "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_redirect'\", function () {", - " var paymentMethods = responseBody.payment_methods;", - " var cardPaymentMethod = paymentMethods.find(function (method) {", - " return method.payment_method == \"bank_redirect\";", - " });", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "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": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], - "url": { - "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - "payment_methods" - ], - "query": [ - { - "key": "client_secret", - "value": "{{client_secret}}" - } - ] - }, - "description": "To filter and list the applicable payment methods for a particular merchant id." - }, - "response": [] - }, - { - "name": "Payments - Confirm", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "//// 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\");", - "})};", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "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": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\",\"email\":\"guest@example.com\"},\"bank_name\":\"ing\"}}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"125.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":7000,\"currency\":\"USD\",\"start_date\":\"2023-04-21T00:00:00Z\",\"end_date\":\"2023-05-21T00:00:00Z\",\"metadata\":{\"frequency\":\"13\"}}}},\"setup_future_usage\":\"off_session\",\"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\":\"128.0.0.1\"}}" - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } - ] - }, - "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" - }, - "response": [] - }, - { - "name": "Payments - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", + "// pm.collectionVariables - Set 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", @@ -19092,12 +17802,6 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, { "key": "publishable_key", "value": "", @@ -20193,102 +18897,1398 @@ "", "// 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.');", - "};", - "", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"stripe\"}}" + }, + "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": "Save card payments - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"adyen\" for \"connector\"", + "if (jsonData?.connector) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", + " function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + " },", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " })};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "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": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" + }, + "response": [] + } + ] + }, + { + "name": "Scenario26-Save card payment with manual capture", + "item": [ + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard_{{random_number}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"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\":\"stripe\"}}" + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// 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 \"Succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// Validate the connector", + "pm.test(\"[POST]::/payments - connector\", function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + "});", + "", + "// 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 \"6000\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",", + " function () {", + " pm.expect(jsonData.amount_received).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 - 540'\",", + " function () {", + " pm.expect(jsonData.amount_capturable).to.eql(0);", + " },", + " );", + "}", + "" + ], + "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 payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + }, + { + "name": "List payment methods for a Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "if (jsonData?.customer_payment_methods[0]?.payment_token) {", + " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);", + " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');", + "}" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/customers/:customer_id/payment_methods", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":customer_id", + "payment_methods" + ], + "query": [ + { + "key": "accepted_country", + "value": "co", + "disabled": true + }, + { + "key": "accepted_country", + "value": "pa", + "disabled": true + }, + { + "key": "accepted_currency", + "value": "voluptate ea", + "disabled": true + }, + { + "key": "accepted_currency", + "value": "exercitation", + "disabled": true + }, + { + "key": "minimum_amount", + "value": "100", + "disabled": true + }, + { + "key": "maximum_amount", + "value": "10000000", + "disabled": true + }, + { + "key": "recurring_payment_enabled", + "value": "true", + "disabled": true + }, + { + "key": "installment_payment_enabled", + "value": "true", + "disabled": true + } + ], + "variable": [ + { + "key": "customer_id", + "value": "{{customer_id}}", + "description": "//Pass the customer id" + } + ] + }, + "description": "To filter and list the applicable payment methods for a particular Customer ID" + }, + "response": [] + }, + { + "name": "Save card payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "if (jsonData?.customer_id) {", + " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", + " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"stripe\"}}" + }, + "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": "Save card payments - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"requires_capture\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " },", + " );", + "}", + "", + "", + "// Response body should have value \"stripe\" for \"connector\"", + "if (jsonData?.connector) {", + " pm.test(", + " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", + " function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + " },", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "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": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"7373\"}" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" + }, + "response": [] + }, + { + "name": "Payments - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/payments/:id/capture - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// Validate the connector", + "pm.test(\"[POST]::/payments - connector\", function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + "});", + "", + "// 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 \"6000\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", + " function () {", + " pm.expect(jsonData.amount_received).to.eql(6540);", + " },", + " );", + "}", + "", + "// Response body should have value \"6540\" for \"amount_capturable\"", + "if (jsonData?.amount_capturable) {", + " pm.test(", + " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",", + " function () {", + " pm.expect(jsonData.amount_capturable).to.eql(6540);", + " },", + " );", + "}", + "" + ], + "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_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/capture", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "capture" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To capture the funds for an uncaptured payment" + }, + "response": [] + }, + { + "name": "Payments - Retrieve-copy", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"Succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// Validate the connector", + "pm.test(\"[POST]::/payments - connector\", function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + "});", + "", + "// 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 \"6000\" for \"amount_received\"", + "if (jsonData?.amount_received) {", + " pm.test(", + " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", + " function () {", + " pm.expect(jsonData.amount_received).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 - 540'\",", + " function () {", + " pm.expect(jsonData.amount_capturable).to.eql(0);", + " },", + " );", + "}", + "" + ], + "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 payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + }, + { + "name": "Refunds - Create Copy", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", + "", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// Response body should have value \"540\" for \"amount\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", + " function () {", + " pm.expect(jsonData.amount).to.eql(540);", + " },", + " );", + "}", + "", + "// Validate the connector", + "pm.test(\"[POST]::/payments - connector\", function () {", + " pm.expect(jsonData.connector).to.eql(\"stripe\");", + "});", + "" + ], + "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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + }, + { + "name": "Refunds - Retrieve Copy", + "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 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);", + "// 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 {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};" + "// Response body should have value \"6540\" for \"amount\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", + " function () {", + " pm.expect(jsonData.amount).to.eql(540);", + " },", + " );", + "}", + "" ], "type": "text/javascript" } } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"stripe\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/refunds/:id", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "refunds", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } ] }, - "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" + "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": "Scenario27-Create payment without customer_id and with billing address and shipping address", + "item": [ { - "name": "Save card payments - Confirm", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "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/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -20337,47 +20337,31 @@ " );", "}", "", - "// Response body should have value \"adyen\" for \"connector\"", - "if (jsonData?.connector) {", + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " })};" + "// 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;", + " },", + ");", + "" ], "type": "text/javascript" } } ], "request": { - "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": [ { @@ -20396,162 +20380,175 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\"}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "confirm" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "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": "Scenario26-Save card payment with manual capture", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// 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(\"[POST]::/payments - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "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(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + "// 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){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", "", "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", + " 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 {{customer_id}}, as jsonData.customer_id is undefined.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", - "}" + "}", + "", + "// 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;", + " },", + ");", + "" ], "type": "text/javascript" } } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard_{{random_number}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"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\":\"stripe\"}}" - }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario28-Confirm a payment with requires_customer_action status", + "item": [ { - "name": "Payments - Retrieve", + "name": "Payments - Create with confirm true", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -20600,50 +20597,24 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// 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 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Validate the connector", - "pm.test(\"[POST]::/payments - connector\", function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - "});", - "", - "// 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 \"6000\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",", " function () {", - " pm.expect(jsonData.amount_received).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", " },", " );", "}", "", - "// 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 - 540'\",", - " function () {", - " pm.expect(jsonData.amount_capturable).to.eql(0);", - " },", - " );", - "}", + "// 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;", + " },", + ");", "" ], "type": "text/javascript" @@ -20651,201 +20622,250 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "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" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "List payment methods for a Customer", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + "// Validate status 2xx", + "pm.test(\"[GET]::/payments/:id - Status code is 400\", function () {", + " pm.response.to.be.error;", "});", "", "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "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){}", + "try {", + " jsonData = pm.response.json();", + "} catch (e) { }", "", - "if (jsonData?.customer_payment_methods[0]?.payment_token) {", - " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);", - " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');", - "}" + "", + "// Response body should have appropriatae error message", + "if (jsonData?.message) {", + " pm.test(", + " \"Content check if appropriate error message is present\",", + " function () {", + " pm.expect(jsonData.message).to.eql(\"You cannot confirm this payment because it has status requires_customer_action\");", + " },", + " );", + "}", + "" ], "type": "text/javascript" } } ], "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:customer_id/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":customer_id", - "payment_methods" - ], - "query": [ - { - "key": "accepted_country", - "value": "co", - "disabled": true - }, - { - "key": "accepted_country", - "value": "pa", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "voluptate ea", - "disabled": true - }, - { - "key": "accepted_currency", - "value": "exercitation", - "disabled": true - }, - { - "key": "minimum_amount", - "value": "100", - "disabled": true - }, + "auth": { + "type": "apikey", + "apikey": [ { - "key": "maximum_amount", - "value": "10000000", - "disabled": true + "key": "value", + "value": "{{publishable_key}}", + "type": "string" }, { - "key": "recurring_payment_enabled", - "value": "true", - "disabled": true + "key": "key", + "value": "api-key", + "type": "string" }, { - "key": "installment_payment_enabled", - "value": "true", - "disabled": true + "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": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/confirm", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "confirm" ], "variable": [ { - "key": "customer_id", - "value": "{{customer_id}}", - "description": "//Pass the customer id" + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" } ] }, - "description": "To filter and list the applicable payment methods for a particular Customer ID" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario29-Create payment with payment method billing", + "item": [ { - "name": "Save card payments - Create", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ - "// Validate status 2xx ", + "// Validate status 2xx", "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", - " pm.response.to.be.success;", + " 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\");", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", "});", "", - "// Validate if response has JSON Body ", + "// Validate if response has JSON Body", "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", + " pm.response.to.have.jsonBody();", "});", "", "// Set response object as internal variable", "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", + "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);", + " 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.');", - "};", - "", + " 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);", + " 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.');", - "};", + " 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);", + " 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.');", - "};", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", "", - "if (jsonData?.customer_id) {", - " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);", - " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');", - "};" + "// Response body should have value \"succeeded\" for \"status\"", + "if (jsonData?.status) {", + " pm.test(", + " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " function () {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + " },", + " );", + "}", + "", + "// 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;", + " },", + ");", + "", + "// Response body should have \"payment_method_data.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", + " .true;", + " },", + ");", + "" ], "type": "text/javascript" } @@ -20870,7 +20890,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -20886,29 +20906,26 @@ "response": [] }, { - "name": "Save card payments - Confirm", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {", + "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(", - " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -20916,7 +20933,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) {}", + "} catch (e) { }", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -20957,26 +20974,33 @@ " );", "}", "", - "// Response body should have value \"requires_capture\" for \"status\"", + "// Response body should have value \"Succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_capture\");", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", + "// 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;", + " },", + ");", "", - "// Response body should have value \"stripe\" for \"connector\"", - "if (jsonData?.connector) {", - " pm.test(", - " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",", - " function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - " },", - " );", - "}", + "// Response body should have \"payment_method_data.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", + " .true;", + " },", + ");", "" ], "type": "text/javascript" @@ -20984,55 +21008,27 @@ } ], "request": { - "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", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"7373\"}" - }, "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ "payments", - ":id", - "confirm" + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } ], "variable": [ { @@ -21042,34 +21038,36 @@ } ] }, - "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" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario30-Update payment with payment method billing", + "item": [ { - "name": "Payments - Capture", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {", + "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/:id/capture - Content-Type is application/json\",", - " function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - " },", - ");", + "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/:id/capture - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -21077,7 +21075,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) {}", + "} catch (e) { }", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -21092,19 +21090,6 @@ " );", "}", "", - "// 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);", @@ -21118,47 +21103,12 @@ " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", + "// Response body should have value \"requires_payment_method\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Validate the connector", - "pm.test(\"[POST]::/payments - connector\", function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - "});", - "", - "// 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 \"6000\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", - " function () {", - " pm.expect(jsonData.amount_received).to.eql(6540);", - " },", - " );", - "}", - "", - "// Response body should have value \"6540\" for \"amount_capturable\"", - "if (jsonData?.amount_capturable) {", - " pm.test(", - " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.amount_capturable).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", @@ -21187,51 +21137,42 @@ "language": "json" } }, - "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { - "raw": "{{baseUrl}}/payments/:id/capture", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } + "payments" ] }, - "description": "To capture the funds for an uncaptured payment" + "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-copy", + "name": "Payments - Update", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -21239,91 +21180,26 @@ "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.\",", - " );", - "}", + "} catch (e) { }", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", - " );", - "}", - "", - "// Validate the connector", - "pm.test(\"[POST]::/payments - connector\", function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - "});", - "", - "// 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 \"6000\" for \"amount_received\"", - "if (jsonData?.amount_received) {", - " pm.test(", - " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.amount_received).to.eql(6540);", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", " },", " );", "}", "", - "// 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 - 540'\",", - " function () {", - " pm.expect(jsonData.amount_capturable).to.eql(0);", - " },", - " );", - "}", + "// Response body should have \"payment_method_data.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", + " .true;", + " },", + ");", "" ], "type": "text/javascript" @@ -21331,15 +21207,28 @@ } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}}}" + }, "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "raw": "{{baseUrl}}/payments/:id", "host": [ "{{baseUrl}}" ], @@ -21347,86 +21236,104 @@ "payments", ":id" ], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], "variable": [ { "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" + "value": "{{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" + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" }, "response": [] }, { - "name": "Refunds - Create Copy", + "name": "Payments - Retrieve", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + "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(\"[POST]::/refunds - Content-Type is application/json\", function () {", + "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) {}", + "} 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);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + "// 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 \"540\" for \"amount\"", + "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",", + " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(540);", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", " },", " );", "}", "", - "// Validate the connector", - "pm.test(\"[POST]::/payments - connector\", function () {", - " pm.expect(jsonData.connector).to.eql(\"stripe\");", - "});", + "// Response body should have \"payment_method_data.billing\"", + "pm.test(", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", + " function () {", + " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", + " .true;", + " },", + ");", "" ], "type": "text/javascript" @@ -21434,93 +21341,120 @@ } ], "request": { - "method": "POST", + "method": "GET", "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, { "key": "Accept", "value": "application/json" } ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" - }, "url": { - "raw": "{{baseUrl}}/refunds", + "raw": "{{baseUrl}}/payments/:id?force_sync=true", "host": [ "{{baseUrl}}" ], "path": [ - "refunds" + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "description": "To create a refund against an already processed payment" + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" }, "response": [] - }, + } + ] + }, + { + "name": "Scenario31-Pass payment method billing in Confirm", + "item": [ { - "name": "Refunds - Retrieve Copy", + "name": "Payments - Create", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + "pm.test(\"[POST]::/payments - 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.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 refund_id as variable for jsonData.payment_id", - "if (jsonData?.refund_id) {", - " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + "// 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 {{refund_id}} as collection variable for value\",", - " jsonData.refund_id,", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", " );", "} else {", " console.log(", - " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", " );", "}", "", - "// Response body should have value \"succeeded\" for \"status\"", - "if (jsonData?.status) {", - " pm.test(", - " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",", - " function () {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - " },", + "// 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.\",", " );", "}", "", - "// Response body should have value \"6540\" for \"amount\"", + "// 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]::/refunds - Content check if value for 'amount' matches '540'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.amount).to.eql(540);", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", @@ -21528,63 +21462,75 @@ ], "type": "text/javascript" } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } } ], "request": { - "method": "GET", + "method": "POST", "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, { "key": "Accept", "value": "application/json" } ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, "url": { - "raw": "{{baseUrl}}/refunds/:id", + "raw": "{{baseUrl}}/payments", "host": [ "{{baseUrl}}" ], "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } + "payments" ] }, - "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" + "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": "Scenario27-Create payment without customer_id and with billing address and shipping address", - "item": [ + }, { - "name": "Payments - Create", + "name": "Payments - Confirm", "event": [ { "listen": "test", "script": { "exec": [ "// Validate status 2xx", - "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + "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 - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", - " \"application/json\",", - " );", - "});", + "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 - Response has JSON Body\", function () {", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", " pm.response.to.have.jsonBody();", "});", "", @@ -21636,21 +21582,21 @@ "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", - "", - "// 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;", - " },", - ");", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ "" ], "type": "text/javascript" @@ -21658,6 +21604,26 @@ } ], "request": { + "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": [ { @@ -21676,18 +21642,27 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}" }, "url": { - "raw": "{{baseUrl}}/payments", + "raw": "{{baseUrl}}/payments/:id/confirm", "host": [ "{{baseUrl}}" ], "path": [ - "payments" + "payments", + ":id", + "confirm" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } ] }, - "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" + "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" }, "response": [] }, @@ -21719,7 +21694,7 @@ "let jsonData = {};", "try {", " jsonData = pm.response.json();", - "} catch (e) {}", + "} catch (e) { }", "", "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", "if (jsonData?.payment_id) {", @@ -21760,21 +21735,21 @@ " );", "}", "", - "// Response body should have value \"Succeeded\" for \"status\"", + "// Response body should have value \"succeeded\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",", + " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",", " function () {", " pm.expect(jsonData.status).to.eql(\"succeeded\");", " },", " );", "}", "", - "// Response body should have \"connector_transaction_id\"", + "// Response body should have \"payment_method_data.billing\"", "pm.test(", - " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",", + " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",", " function () {", - " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be", + " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be", " .true;", " },", ");",
2024-03-05T04:09:55Z
## Description <!-- Describe your changes in detail --> This PR is a fix for postman CI failing due a bug introduced in https://github.com/juspay/hyperswitch/pull/3807. As we can see here in CI's commit, https://github.com/juspay/hyperswitch/commit/cd7040fa8cad2e69a53e3ed609c9eb8a8a17495a, it is clear that NMI and Stripe collection are the ones that are affected which again can be confirmed with https://github.com/juspay/hyperswitch/actions/runs/8148897592/job/22272607599 Closes #3955 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> People are shouting that the collections are failing. We've to keep them calm. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> NMI <img width="478" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/0f1aa4d9-5bf2-4014-9b5d-00ac992ead9e"> Stripe <img width="491" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/4c8a2d3b-cd5e-41de-b4aa-d91dc9f00149">
2b0fbc70749338d5c501bbb782d6fc4747890d61
NMI <img width="478" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/0f1aa4d9-5bf2-4014-9b5d-00ac992ead9e"> Stripe <img width="491" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/4c8a2d3b-cd5e-41de-b4aa-d91dc9f00149">
[ "crates/test_utils/src/main.rs", "postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json", "postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json", "postma...
juspay/hyperswitch
juspay__hyperswitch-3741
Bug: Merchant Payment Method List changes for wallet restrictions Since we are currently not getting any differentiators for multiple mandates set via a single wallet, we will be restricting setting up recurring payment for wallet only once. - In Merchant Payment Method list, wallet types which are already saved and in active state for a customer should not be listed
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..8d54a6be408 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1316,6 +1316,47 @@ pub async fn list_payment_methods( .await?; } + // Filter out applepay payment method from mca if customer has already saved it + response + .iter() + .position(|pm| { + pm.payment_method == enums::PaymentMethod::Wallet + && pm.payment_method_type == enums::PaymentMethodType::ApplePay + }) + .as_ref() + .zip(customer.as_ref()) + .async_map(|(index, customer)| async { + match db + .find_payment_method_by_customer_id_merchant_id_list( + &customer.customer_id, + &merchant_account.merchant_id, + None, + ) + .await + { + Ok(customer_payment_methods) => { + if customer_payment_methods.iter().any(|pm| { + pm.payment_method == enums::PaymentMethod::Wallet + && pm.payment_method_type == Some(enums::PaymentMethodType::ApplePay) + }) { + response.remove(*index); + } + Ok(()) + } + Err(error) => { + if error.current_context().is_db_not_found() { + Ok(()) + } else { + Err(error) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to find payment methods for a customer") + } + } + } + }) + .await + .transpose()?; + let mut pmt_to_auth_connector = HashMap::new(); if let Some((payment_attempt, payment_intent)) =
2024-03-04T14:39:43Z
## Description <!-- Describe your changes in detail --> Since we are currently not getting any differentiators for multiple mandates set via a single wallet, we will be restricting setting up recurring payment for wallet only once. - In Merchant Payment Method list, wallet types which are already saved and in active state for a customer should not be listed ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. Applepay shoudn't be listed in the result (Applepay is configured in merchant MCA and applepay payment method exists for customer, hence it has to be filtered)
087932f06044454570c971def0e82dc3d838598c
1. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. Applepay shoudn't be listed in the result (Applepay is configured in merchant MCA and applepay payment method exists for customer, hence it has to be filtered)
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3948
Bug: fix: Enforce uniqueness of groups in custom role assignments Permission groups should be unique while creating/updating custom role.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 6b25b692c12..643d8ac975e 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2327,6 +2327,7 @@ pub enum RoleScope { Debug, Eq, PartialEq, + Hash, serde::Serialize, serde::Deserialize, strum::Display, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index bb83b82f2da..c9d112f2566 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::user_role as user_role_api; use common_enums::PermissionGroup; use error_stack::ResultExt; @@ -48,11 +50,18 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { .attach_printable("Role groups cannot be empty"); } - if groups.contains(&PermissionGroup::OrganizationManage) { + let unique_groups: HashSet<_> = groups.iter().cloned().collect(); + + if unique_groups.contains(&PermissionGroup::OrganizationManage) { return Err(UserErrors::InvalidRoleOperation.into()) .attach_printable("Organization manage group cannot be added to role"); } + if unique_groups.len() != groups.len() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Duplicate permission group found"); + } + Ok(()) }
2024-03-04T13:37:03Z
## Description Enforce uniqueness of groups while role create or update. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Currently duplicate groups are allowed while role create/update. ## How did you test it? Try to create/update role with duplicate groups: Create ``` curl --location 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test007", "groups": ["operations_view", "operations_manage", "operations_manage"], "role_scope": "organization" }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ``` Update ``` curl --location --request PUT 'http://localhost:8080/user/role/role_DGLY2gKDdS48cFoY573Y' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "groups": ["operations_view", "operations_view"] }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ```
f132527490a7d8cd8469573d8e6856f33974959f
Try to create/update role with duplicate groups: Create ``` curl --location 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test007", "groups": ["operations_view", "operations_manage", "operations_manage"], "role_scope": "organization" }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ``` Update ``` curl --location --request PUT 'http://localhost:8080/user/role/role_DGLY2gKDdS48cFoY573Y' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "groups": ["operations_view", "operations_view"] }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ```
[ "crates/common_enums/src/enums.rs", "crates/router/src/utils/user_role.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3612
Bug: [FEATURE] Incorporate Open Banking flows in Payments Core ### Feature Description Need to support Open banking framework in Payments core to handle integrations of open banking connectors ### Possible Implementation Will be using the payments core for implementation of open banking payment flows ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bcc67100e1c..f53507fc13a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1600,6 +1600,7 @@ mod payment_method_data_serde { | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } @@ -1657,6 +1658,8 @@ pub enum PaymentMethodData { GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), + #[schema(title = "OpenBanking")] + OpenBanking(OpenBankingData), } pub trait GetAddressFromPaymentMethodData { @@ -1680,6 +1683,7 @@ impl GetAddressFromPaymentMethodData for PaymentMethodData { | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) + | Self::OpenBanking(_) | Self::MandatePayment => None, } } @@ -1717,6 +1721,7 @@ impl PaymentMethodData { Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), + Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::CardToken(_) | Self::MandatePayment => None, } } @@ -1785,6 +1790,14 @@ impl GetPaymentMethodType for PayLaterData { } } +impl GetPaymentMethodType for OpenBankingData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, + } + } +} + impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { @@ -1983,6 +1996,7 @@ pub enum AdditionalPaymentData { Voucher {}, CardRedirect {}, CardToken {}, + OpenBanking {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -2673,6 +2687,12 @@ pub struct SamsungPayWalletData { pub token: Secret<String>, } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum OpenBankingData { + #[serde(rename = "open_banking_pis")] + OpenBankingPIS {}, +} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { @@ -2946,6 +2966,7 @@ where | PaymentMethodDataResponse::Upi {} | PaymentMethodDataResponse::Wallet {} | PaymentMethodDataResponse::BankTransfer {} + | PaymentMethodDataResponse::OpenBanking {} | PaymentMethodDataResponse::Voucher {} => { payment_method_data_response.serialize(serializer) } @@ -2979,6 +3000,7 @@ pub enum PaymentMethodDataResponse { GiftCard {}, CardRedirect {}, CardToken {}, + OpenBanking {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] @@ -4146,6 +4168,7 @@ impl From<AdditionalPaymentData> for PaymentMethodDataResponse { AdditionalPaymentData::GiftCard {} => Self::GiftCard {}, AdditionalPaymentData::CardRedirect {} => Self::CardRedirect {}, AdditionalPaymentData::CardToken {} => Self::CardToken {}, + AdditionalPaymentData::OpenBanking {} => Self::OpenBanking {}, } } } @@ -4531,6 +4554,8 @@ pub enum SessionToken { Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), + /// Session token for OpenBanking PIS flow + OpenBanking(OpenBankingSessionToken), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } @@ -4607,6 +4632,13 @@ pub struct PaypalSessionTokenResponse { pub sdk_next_action: SdkNextAction, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct OpenBankingSessionToken { + /// The session token for OpenBanking Connectors + pub open_banking_session_token: String, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 129e83ce2b6..12281350af2 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1569,6 +1569,8 @@ pub enum PaymentMethodType { PayEasy, LocalBankTransfer, Mifinity, + #[serde(rename = "open_banking_pis")] + OpenBankingPIS, } /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. @@ -1606,6 +1608,7 @@ pub enum PaymentMethod { Upi, Voucher, GiftCard, + OpenBanking, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index fc39cd1cf50..fab570542c8 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1882,6 +1882,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::FamilyMart => Self::Voucher, PaymentMethodType::Seicomart => Self::Voucher, PaymentMethodType::PayEasy => Self::Voucher, + PaymentMethodType::OpenBankingPIS => Self::OpenBanking, } } } diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs index 38dc4130cf0..06f9d25b65d 100644 --- a/crates/connector_configs/src/response_modifier.rs +++ b/crates/connector_configs/src/response_modifier.rs @@ -19,6 +19,7 @@ impl ConnectorApiIntegrationPayload { let mut voucher_details: Vec<Provider> = Vec::new(); let mut gift_card_details: Vec<Provider> = Vec::new(); let mut card_redirect_details: Vec<Provider> = Vec::new(); + let mut open_banking_details: Vec<Provider> = Vec::new(); if let Some(payment_methods_enabled) = response.payment_methods_enabled.clone() { for methods in payment_methods_enabled { @@ -160,6 +161,18 @@ impl ConnectorApiIntegrationPayload { } } } + api_models::enums::PaymentMethod::OpenBanking => { + if let Some(payment_method_types) = methods.payment_method_types { + for method_type in payment_method_types { + open_banking_details.push(Provider { + payment_method_type: method_type.payment_method_type, + accepted_currencies: method_type.accepted_currencies.clone(), + accepted_countries: method_type.accepted_countries.clone(), + payment_experience: method_type.payment_experience, + }) + } + } + } api_models::enums::PaymentMethod::Upi => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 1a54dc9ae0d..fe39da67a93 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -138,6 +138,7 @@ impl DashboardRequestPayload { | PaymentMethod::Upi | PaymentMethod::Voucher | PaymentMethod::GiftCard + | PaymentMethod::OpenBanking | PaymentMethod::CardRedirect => { if let Some(provider) = payload.provider { let val = Self::transform_payment_method( diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 008b5628512..13e11515382 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -69,6 +69,7 @@ impl cgraph::NodeViz for dir::DirValue { Self::SetupFutureUsage(sfu) => sfu.to_string(), Self::CardRedirectType(crt) => crt.to_string(), Self::RealTimePaymentType(rtpt) => rtpt.to_string(), + Self::OpenBankingType(ob) => ob.to_string(), } } } diff --git a/crates/euclid/src/frontend/ast/lowering.rs b/crates/euclid/src/frontend/ast/lowering.rs index 48a1a0ab8bf..8a8ba695e9f 100644 --- a/crates/euclid/src/frontend/ast/lowering.rs +++ b/crates/euclid/src/frontend/ast/lowering.rs @@ -264,6 +264,8 @@ fn lower_comparison_inner<O: EuclidDirFilter>( dir::DirKeyKind::UpiType => lower_enum!(UpiType, value), + dir::DirKeyKind::OpenBankingType => lower_enum!(OpenBankingType, value), + dir::DirKeyKind::VoucherType => lower_enum!(VoucherType, value), dir::DirKeyKind::GiftCardType => lower_enum!(GiftCardType, value), diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index a21ae104882..8cfdf656716 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -319,6 +319,13 @@ pub enum DirKeyKind { props(Category = "Payment Method Types") )] RealTimePaymentType, + #[serde(rename = "open_banking")] + #[strum( + serialize = "open_banking", + detailed_message = "Supported types of open banking payment method", + props(Category = "Payment Method Types") + )] + OpenBankingType, } pub trait EuclidDirFilter: Sized @@ -367,6 +374,7 @@ impl DirKeyKind { Self::SetupFutureUsage => types::DataType::EnumVariant, Self::CardRedirectType => types::DataType::EnumVariant, Self::RealTimePaymentType => types::DataType::EnumVariant, + Self::OpenBankingType => types::DataType::EnumVariant, } } pub fn get_value_set(&self) -> Option<Vec<DirValue>> { @@ -498,6 +506,11 @@ impl DirKeyKind { .map(DirValue::RealTimePaymentType) .collect(), ), + Self::OpenBankingType => Some( + enums::OpenBankingType::iter() + .map(DirValue::OpenBankingType) + .collect(), + ), } } } @@ -565,6 +578,8 @@ pub enum DirValue { CardRedirectType(enums::CardRedirectType), #[serde(rename = "real_time_payment")] RealTimePaymentType(enums::RealTimePaymentType), + #[serde(rename = "open_banking")] + OpenBankingType(enums::OpenBankingType), } impl DirValue { @@ -599,6 +614,7 @@ impl DirValue { Self::VoucherType(_) => (DirKeyKind::VoucherType, None), Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None), Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None), + Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None), }; DirKey::new(kind, data) @@ -634,6 +650,7 @@ impl DirValue { Self::SetupFutureUsage(_) => None, Self::CardRedirectType(_) => None, Self::RealTimePaymentType(_) => None, + Self::OpenBankingType(_) => None, } } diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 5d0defc7357..0d2f959c702 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -160,6 +160,26 @@ pub enum BankRedirectType { Przelewy24, Trustly, } + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + strum::Display, + strum::VariantNames, + strum::EnumIter, + strum::EnumString, + serde::Serialize, + serde::Deserialize, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum OpenBankingType { + OpenBankingPIS, +} + #[derive( Clone, Debug, @@ -350,3 +370,4 @@ collect_variants!(VoucherType); collect_variants!(GiftCardType); collect_variants!(BankTransferType); collect_variants!(CardRedirectType); +collect_variants!(OpenBankingType); diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index f91c63a8166..33d368e9696 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -168,6 +168,14 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { } } +impl From<enums::OpenBankingType> for global_enums::PaymentMethodType { + fn from(value: enums::OpenBankingType) -> Self { + match value { + enums::OpenBankingType::OpenBankingPIS => Self::OpenBankingPIS, + } + } +} + impl From<enums::CryptoType> for global_enums::PaymentMethodType { fn from(value: enums::CryptoType) -> Self { match value { @@ -238,6 +246,7 @@ fn lower_value(dir_value: dir::DirValue) -> Result<EuclidValue, AnalysisErrorTyp dir::DirValue::RewardType(rt) => EuclidValue::PaymentMethodType(rt.into()), dir::DirValue::BusinessLabel(bl) => EuclidValue::BusinessLabel(bl), dir::DirValue::SetupFutureUsage(sfu) => EuclidValue::SetupFutureUsage(sfu), + dir::DirValue::OpenBankingType(ob) => EuclidValue::PaymentMethodType(ob.into()), }) } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 3f83ee3db01..3e35bcd391c 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -38,6 +38,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Bacs => match self.1 { @@ -53,6 +54,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), @@ -69,6 +71,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), @@ -182,6 +185,9 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet } global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), + global_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index e92552002b5..031440ae541 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -263,6 +263,7 @@ pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> { dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS, dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS, dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS, + dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS, dir::DirKeyKind::PaymentAmount | dir::DirKeyKind::Connector diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 005e21743d9..49b6951f5f8 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -22,6 +22,7 @@ pub enum PaymentMethodData { Voucher(VoucherData), GiftCard(Box<GiftCardData>), CardToken(CardToken), + OpenBanking(OpenBankingData), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -46,6 +47,7 @@ impl PaymentMethodData { Self::Upi(_) => Some(common_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard), + Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking), Self::CardToken(_) | Self::MandatePayment => None, } } @@ -318,6 +320,12 @@ pub enum BankRedirectData { LocalBankRedirect {}, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum OpenBankingData { + OpenBankingPIS {}, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct CryptoData { @@ -495,6 +503,9 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { api_models::payments::PaymentMethodData::CardToken(card_token) => { Self::CardToken(From::from(card_token)) } + api_models::payments::PaymentMethodData::OpenBanking(ob_data) => { + Self::OpenBanking(From::from(ob_data)) + } } } } @@ -922,3 +933,11 @@ impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData { } } } + +impl From<api_models::payments::OpenBankingData> for OpenBankingData { + fn from(value: api_models::payments::OpenBankingData) -> Self { + match value { + api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {}, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index 046866beea5..1263f8f975a 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -46,3 +46,6 @@ pub struct PreProcessing; #[derive(Debug, Clone)] pub struct IncrementalAuthorization; + +#[derive(Debug, Clone)] +pub struct PostProcessing; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index f30e6010cff..26db7eed01d 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -54,7 +54,7 @@ pub struct PaymentsAuthorizeData { pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, - pub customer_id: Option<String>, + pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, @@ -336,6 +336,35 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { }) } } + +#[derive(Debug, Clone)] +pub struct PaymentsPostProcessingData { + pub payment_method_data: PaymentMethodData, + pub customer_id: Option<id_type::CustomerId>, + pub connector_transaction_id: Option<String>, +} + +impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> + for PaymentsPostProcessingData +{ + type Error = error_stack::Report<ApiErrorResponse>; + + fn try_from( + data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: data.request.payment_method_data, + connector_transaction_id: match data.response { + Ok(response_types::PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(id), + .. + }) => Some(id.clone()), + _ => None, + }, + customer_id: data.request.customer_id, + }) + } +} #[derive(Debug, Clone)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<PaymentMethodData>, diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index a5c6aafdab1..e41b0aa78b9 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -65,6 +65,9 @@ pub enum PaymentsResponseData { error_code: Option<String>, error_message: Option<String>, }, + PostProcessingResponse { + session_token: Option<api_models::payments::OpenBankingSessionToken>, + }, } #[derive(serde::Serialize, Debug, Clone)] diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 0cbf171495b..5b31a6be648 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -143,6 +143,9 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), + api_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } @@ -416,9 +419,11 @@ fn global_vec_pmt( global_vector.append(collect_global_variants!(GiftCardType)); global_vector.append(collect_global_variants!(BankTransferType)); global_vector.append(collect_global_variants!(CardRedirectType)); + global_vector.append(collect_global_variants!(OpenBankingType)); global_vector.push(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); + let global_vector = global_vector .into_iter() .filter(|global_value| !enabled_pmt.contains(global_value)) diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 1b1bd931200..758a0dd3de0 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -103,6 +103,7 @@ impl IntoDirValue for api_enums::PaymentMethod { Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)), Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)), Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)), + Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)), } } } @@ -158,6 +159,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -175,6 +177,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -193,6 +196,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -300,6 +304,9 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), + api_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index d2e669175eb..233f43b0846 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -557,6 +557,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentChargeResponse, api_models::refunds::ChargeRefunds, api_models::payments::CustomerDetailsResponse, + api_models::payments::OpenBankingData, + api_models::payments::OpenBankingSessionToken, )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 81dbbb748e3..62cf9416b24 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -864,6 +864,7 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index db5ada51529..b5408f600b4 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -418,6 +418,7 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index c9f81ec722b..175138add75 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -447,6 +447,7 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Aci"), diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 4fee5ea9bb0..9122f579656 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -223,7 +223,8 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::UpiIntent | PaymentMethodType::VietQr | PaymentMethodType::Mifinity - | PaymentMethodType::LocalBankRedirect => { + | PaymentMethodType::LocalBankRedirect + | PaymentMethodType::OpenBankingPIS => { capture_method_not_supported!(connector, capture_method, payment_method_type) } }, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 6b0e251691e..4d3855654ad 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1581,6 +1581,7 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), @@ -2575,6 +2576,7 @@ impl<'a> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index fcb492bedfa..9fab84559b5 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -204,6 +204,7 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 651054552f8..33570a782fd 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -342,6 +342,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), @@ -520,6 +521,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( @@ -578,6 +580,7 @@ impl | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 6bb96f5e9bf..b2e9b1a032e 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -185,6 +185,7 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bambora"), diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index c0434572ce1..34244bbb819 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -321,6 +321,7 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), @@ -395,6 +396,7 @@ impl<F, T> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; @@ -1070,6 +1072,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( @@ -1557,6 +1560,7 @@ impl<F> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; @@ -1773,6 +1777,7 @@ impl<F> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index c00303fc5e9..4a4521f31a0 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -103,6 +103,7 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest { | domain::payments::PaymentMethodData::Upi(_) | domain::payments::PaymentMethodData::Voucher(_) | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("billwerk"), diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index d1d5f1d8c9e..f354bf1c2db 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -233,6 +233,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), @@ -397,6 +398,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index a1a239a6e1b..a8b4d8c0ec2 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -92,6 +92,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BokuPaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("boku"), diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index d52328a7783..af50bd10ce7 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -209,6 +209,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), @@ -241,6 +242,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> | api_models::enums::PaymentMethod::RealTimePayment | api_models::enums::PaymentMethod::Upi | api_models::enums::PaymentMethod::Voucher + | api_models::enums::PaymentMethod::OpenBanking | api_models::enums::PaymentMethod::GiftCard => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( @@ -994,6 +996,7 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), @@ -1584,6 +1587,7 @@ fn get_braintree_redirect_form( | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err( errors::ConnectorError::NotImplemented("given payment method".to_owned()), )?, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 7fc34e75f97..717c4afc195 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -175,6 +175,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index e035c102d20..db09e93701b 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -131,6 +131,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), @@ -367,6 +368,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 215003f8fb2..c15afd7fd44 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -78,6 +78,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("CryptoPay"), diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 1cd6066ad69..2f286964e3e 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -214,6 +214,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), @@ -1384,6 +1385,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), @@ -1490,6 +1492,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), @@ -2208,6 +2211,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), @@ -2317,6 +2321,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs index bb8c85b77da..9c4ab6cf6a6 100644 --- a/crates/router/src/connector/datatrans/transformers.rs +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -193,6 +193,7 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message("Datatrans"), diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index b018dbcd2e9..ca18d12a088 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -166,6 +166,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( crate::connector::utils::get_unimplemented_payment_method_error_message( diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index eee518187a2..1a149c6af78 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -188,6 +188,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("fiserv"), diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 637a3acd1e1..0533d71ffeb 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -115,6 +115,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Forte"), diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index 3cf1204a697..8974c9f94b9 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -73,6 +73,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobepayPaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("globepay"), diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index d31d985500a..fb27f5138a9 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -246,6 +246,7 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), @@ -415,6 +416,7 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index f882b341f63..2f6cf61e759 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -163,6 +163,7 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Helcim"), @@ -265,6 +266,7 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Helcim"), diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 71aeed0f7dd..1ce07fb49e3 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -204,7 +204,8 @@ impl | domain::PaymentMethodData::Reward | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("iatapay"), ))? diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 4796f15cb64..fbfb8b71974 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -628,7 +628,8 @@ impl | common_enums::PaymentMethodType::Fps | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay - | common_enums::PaymentMethodType::VietQr, + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", @@ -649,6 +650,7 @@ impl | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) => { Err(report!(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 5d18834de86..0e52f7d3b50 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -196,6 +196,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Mifinity"), diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 2daf83cbacf..ac0a04de182 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -606,6 +606,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), @@ -786,7 +787,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index c25da631b71..7e32ae5ebed 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -625,6 +625,7 @@ fn get_payment_details_and_product( | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index a87b8e6176d..e0858e16a4a 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -584,6 +584,7 @@ impl | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nmi"), diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 6de5ba5e6d1..8336cbf1318 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -352,6 +352,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( conn_utils::get_unimplemented_payment_method_error_message("Noon"), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index a23a05e34e3..1aa34517357 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -995,6 +995,7 @@ where | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), @@ -1196,6 +1197,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> | Some(domain::PaymentMethodData::Reward) | Some(domain::PaymentMethodData::RealTimePayment(..)) | Some(domain::PaymentMethodData::Upi(..)) + | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index b6c05dff2d3..5771b45100b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -56,6 +56,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Opayo"), diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index c2d8e0dfddb..8da3e7502be 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -137,6 +137,7 @@ impl TryFrom<&PayeezyRouterData<&types::PaymentsAuthorizeRouterData>> for Payeez | diesel_models::enums::PaymentMethod::RealTimePayment | diesel_models::enums::PaymentMethod::Upi | diesel_models::enums::PaymentMethod::Voucher + | diesel_models::enums::PaymentMethod::OpenBanking | diesel_models::enums::PaymentMethod::GiftCard => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } @@ -259,6 +260,7 @@ fn get_payment_method_data( | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Payeezy"), ))?, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 47942d7de43..2ec35b7a7de 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -429,6 +429,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } @@ -673,6 +674,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("payme"), ))?, @@ -732,6 +734,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { | Some(PaymentMethodData::Upi(_)) | Some(PaymentMethodData::Voucher(_)) | Some(PaymentMethodData::GiftCard(_)) + | Some(PaymentMethodData::OpenBanking(_)) | Some(PaymentMethodData::CardToken(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) @@ -771,6 +774,7 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 283b6c80a8e..9718fd5a8de 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -551,6 +551,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Crypto(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index 50813a81629..6ecaabd3fe6 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -151,6 +151,7 @@ impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Placetopay"), diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 6fe1a7173be..40fe8235956 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -116,6 +116,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs index 5618c85d531..8cf32891886 100644 --- a/crates/router/src/connector/razorpay/transformers.rs +++ b/crates/router/src/connector/razorpay/transformers.rs @@ -398,6 +398,7 @@ impl | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 80ef0daaf21..f384d8d296d 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -247,6 +247,7 @@ where | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), @@ -469,6 +470,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(domain::PaymentMethodData::Reward) | Some(domain::PaymentMethodData::RealTimePayment(_)) | Some(domain::PaymentMethodData::Upi(_)) + | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(_)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 15de18c8890..67be82bb2d9 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -174,6 +174,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), @@ -290,6 +291,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 65ee90830a3..d814deef264 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -108,6 +108,7 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Stax"), @@ -260,6 +261,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Stax"), diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index aa792db04bd..2524a1aeacf 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -704,6 +704,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingUk + | enums::PaymentMethodType::OpenBankingPIS | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pse @@ -1330,6 +1331,7 @@ fn create_stripe_payment_method( domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -1706,6 +1708,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent | domain::payments::PaymentMethodData::Upi(_) | domain::payments::PaymentMethodData::Voucher(_) | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), @@ -3281,6 +3284,7 @@ impl | Some(domain::PaymentMethodData::GiftCard(..)) | Some(domain::PaymentMethodData::CardRedirect(..)) | Some(domain::PaymentMethodData::Voucher(..)) + | Some(domain::PaymentMethodData::OpenBanking(..)) | Some(domain::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), @@ -3734,6 +3738,7 @@ impl | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 77d85393d29..85539e253b7 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -433,6 +433,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index cea51ce77e1..53561d93a92 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -76,6 +76,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("tsys"), diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index d56de472eb3..3377a946fbd 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2668,6 +2668,7 @@ pub enum PaymentMethodDataType { Fps, PromptPay, VietQr, + OpenBanking, } impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { @@ -2848,6 +2849,9 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, + domain::payments::PaymentMethodData::OpenBanking(data) => match data { + hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking + }, } } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 12064fdf0f4..ac55f55d536 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -150,6 +150,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Volt"), diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index fe1bcab0bb2..365ddda4d53 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -249,6 +249,7 @@ impl | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 5caf6b0e1f1..892b6644722 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -108,6 +108,7 @@ fn fetch_payment_instrument( | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 026c39f0e3e..2562277ee9b 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -694,6 +694,7 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index f44d46cd8e0..ada1de0e618 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -181,7 +181,8 @@ impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPayment | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message( item.router_data.connector.as_str(), diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 0d0eace13e3..331eb430211 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -91,6 +91,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .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 d897b9e6339..47ab1810f75 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -13,11 +13,14 @@ use crate::{ }, errors, services, types::{ - api::fraud_check::{self as frm_api, FraudCheckConnectorData}, + api::{ + self, + fraud_check::{self as frm_api, FraudCheckConnectorData}, + }, domain, fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData}, storage::enums as storage_enums, - BrowserInformation, ConnectorAuthType, ResponseId, RouterData, + BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -34,6 +37,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -135,6 +139,17 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] 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 b44f2d3d4fc..2f263124083 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -11,13 +11,13 @@ use crate::{ }, errors, services, types::{ - api::RecordReturn, + api::{self, RecordReturn}, domain, fraud_check::{ FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, utils, SessionState, }; @@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -107,6 +108,17 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] 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 907b941ee67..fee1964a42a 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -11,11 +11,11 @@ use crate::{ }, errors, services, types::{ - api::fraud_check as frm_api, + api::{self, fraud_check as frm_api}, domain, fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData}, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -32,6 +32,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -116,6 +117,17 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] 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 dd042a6b593..c5d00c4a8e9 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -10,13 +10,13 @@ use crate::{ }, errors, services, types::{ - api::fraud_check as frm_api, + api::{self, fraud_check as frm_api}, domain, fraud_check::{ FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -37,6 +37,7 @@ impl _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { @@ -120,6 +121,17 @@ impl Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a7a87b6d96e..00b51b9f09e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -71,6 +71,7 @@ pub async fn retrieve_payment_method( pm @ Some(api::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)), pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)), pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => { let payment_token = helpers::store_payment_method_data_in_vault( state, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ccca6eaed60..2e197516ed6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -27,7 +27,7 @@ use api_models::{ }; use common_utils::{ ext_traits::{AsyncExt, StringExt}, - pii, + id_type, pii, types::{MinorUnit, Surcharge}, }; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; @@ -41,7 +41,7 @@ pub use hyperswitch_domain_models::{ router_data::RouterData, router_request_types::CustomerDetails, }; -use masking::{ExposeInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use redis_interface::errors::RedisError; use router_env::{instrument, metrics::add_attributes, tracing}; #[cfg(feature = "olap")] @@ -74,6 +74,7 @@ use crate::{ core::{ authentication as authentication_core, errors::{self, CustomResult, RouterResponse, RouterResult}, + payment_methods::cards, utils, }, db::StorageInterface, @@ -285,7 +286,7 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, @@ -307,6 +308,9 @@ where ) .await?; + let op_ref = &operation; + let should_trigger_post_processing_flows = is_operation_confirm(&operation); + let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; @@ -326,7 +330,7 @@ where ) .await?; - operation + let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -336,7 +340,23 @@ where &key_store, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } ConnectorCallType::Retryable(connectors) => { @@ -357,7 +377,7 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, @@ -414,6 +434,9 @@ where }; } + let op_ref = &operation; + let should_trigger_post_processing_flows = is_operation_confirm(&operation); + let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; @@ -432,7 +455,7 @@ where ) .await?; - operation + let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -442,7 +465,23 @@ where &key_store, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector_data, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } ConnectorCallType::SessionMultiple(connectors) => { @@ -1400,7 +1439,10 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest>( frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &storage::business_profile::BusinessProfile, is_retry_payment: bool, -) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> where F: Send + Clone + Sync, RouterDReq: Send + Sync, @@ -1461,6 +1503,16 @@ where ) .await?; + let merchant_recipient_data = payment_data + .get_merchant_recipient_data( + state, + merchant_account, + key_store, + &merchant_connector_account, + &connector, + ) + .await?; + let mut router_data = payment_data .construct_router_data( state, @@ -1469,6 +1521,7 @@ where key_store, customer, &merchant_connector_account, + merchant_recipient_data, ) .await?; @@ -1611,7 +1664,7 @@ where ) .await?; - let router_data_res = if should_continue_further { + let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, @@ -1629,13 +1682,75 @@ where .await } else { Ok(router_data) - }; + }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); - router_data_res + Ok((router_data, merchant_connector_account)) +} + +pub async fn get_merchant_bank_data_for_open_banking_connectors( + merchant_connector_account: &helpers::MerchantConnectorAccountType, + key_store: &domain::MerchantKeyStore, + connector: &api::ConnectorData, + state: &SessionState, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<Option<router_types::MerchantRecipientData>> { + let merchant_data = merchant_connector_account + .get_additional_merchant_data() + .get_required_value("additional_merchant_data")? + .into_inner() + .peek() + .clone(); + + let merchant_recipient_data = merchant_data + .parse_value::<router_types::AdditionalMerchantData>("AdditionalMerchantData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decode MerchantRecipientData")?; + + let connector_name = enums::Connector::to_string(&connector.connector_name); + let locker_based_connector_list = state.conf.locker_based_open_banking_connectors.clone(); + let contains = locker_based_connector_list + .connector_list + .contains(connector_name.as_str()); + + let recipient_id = helpers::get_recipient_id_for_open_banking(&merchant_recipient_data)?; + 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()) + .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(), + id.as_str(), + Some(enums::LockerChoice::HyperswitchCardVault), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Merchant bank account data could not be fetched from locker")?; + + let parsed: router_types::MerchantAccountData = locker_resp + .peek() + .to_string() + .parse_struct("MerchantAccountData") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Some(router_types::MerchantRecipientData::AccountData(parsed)) + } else { + Some(router_types::MerchantRecipientData::ConnectorRecipientId( + Secret::new(id), + )) + } + } else { + None + }; + Ok(final_recipient_data) } async fn blocklist_guard<F, ApiRequest>( @@ -1743,6 +1858,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .await?; @@ -1875,6 +1991,7 @@ where key_store, customer, merchant_connector_account, + None, ) .await?; @@ -2043,6 +2160,69 @@ where Ok(router_data_and_should_continue_payment) } +#[allow(clippy::too_many_arguments)] +async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq>( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + customer: &Option<domain::Customer>, + merchant_conn_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + payment_data: &mut PaymentData<F>, + _operation: &BoxedOperation<'_, F, Q>, +) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +where + F: Send + Clone + Sync, + RouterDReq: Send + Sync, + + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, + PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, +{ + let mut router_data = payment_data + .construct_router_data( + state, + connector.connector.id(), + merchant_account, + key_store, + customer, + merchant_conn_account, + None, + ) + .await?; + + match payment_data.payment_method_data.clone() { + Some(api_models::payments::PaymentMethodData::OpenBanking( + api_models::payments::OpenBankingData::OpenBankingPIS { .. }, + )) => { + if connector.connector_name == router_types::Connector::Plaid { + router_data = router_data.postprocessing_steps(state, connector).await?; + let token = if let Ok(ref res) = router_data.response { + match res { + router_types::PaymentsResponseData::PostProcessingResponse { + session_token, + } => session_token + .as_ref() + .map(|token| api::SessionToken::OpenBanking(token.clone())), + _ => None, + } + } else { + None + }; + if let Some(t) = token { + payment_data.sessions_token.push(t); + } + + Ok(router_data) + } else { + Ok(router_data) + } + } + _ => Ok(router_data), + } +} + pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } 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 178b14dde54..fbedca14aeb 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -40,6 +40,8 @@ mod dummy_connector_default_impl { impl<const T: u8> api::PaymentsPreProcessingV2 for connector::DummyConnector<T> {} + impl<const T: u8> api::PaymentsPostProcessingV2 for connector::DummyConnector<T> {} + impl<const T: u8> services::ConnectorIntegrationV2< api::Authorize, @@ -170,6 +172,16 @@ mod dummy_connector_default_impl { { } + impl<const T: u8> + services::ConnectorIntegrationV2< + api::PostProcessing, + types::PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> + { + } + impl<const T: u8> services::ConnectorIntegrationV2< api::AuthorizeSessionToken, @@ -544,6 +556,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl api::PaymentTokenV2 for $path::$connector{} impl api::ConnectorCustomerV2 for $path::$connector{} impl api::PaymentsPreProcessingV2 for $path::$connector{} + impl api::PaymentsPostProcessingV2 for $path::$connector{} impl services::ConnectorIntegrationV2<api::Authorize,types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData> for $path::$connector{} @@ -603,6 +616,12 @@ macro_rules! default_imp_for_new_connector_integration_payment { types::PaymentsPreProcessingData, types::PaymentsResponseData, > for $path::$connector{} + impl services::ConnectorIntegrationV2< + api::PostProcessing, + types::PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for $path::$connector{} impl services::ConnectorIntegrationV2< api::AuthorizeSessionToken, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 815b02285dd..53ca8d02451 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -25,6 +25,7 @@ use crate::{ }; #[async_trait] +#[allow(clippy::too_many_arguments)] pub trait ConstructFlowSpecificData<F, Req, Res> { async fn construct_router_data<'a>( &self, @@ -34,7 +35,17 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, Req, Res>>; + + async fn get_merchant_recipient_data<'a>( + &self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>>; } #[allow(clippy::too_many_arguments)] @@ -110,6 +121,19 @@ pub trait Feature<F, T> { Ok(self) } + async fn postprocessing_steps<'a>( + self, + _state: &SessionState, + _connector: &api::ConnectorData, + ) -> RouterResult<Self> + where + F: Clone, + Self: Sized, + dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, + { + Ok(self) + } + async fn create_connector_customer<'a>( &self, _state: &SessionState, @@ -970,6 +994,21 @@ macro_rules! default_imp_for_pre_processing_steps{ }; } +macro_rules! default_imp_for_post_processing_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl api::PaymentsPostProcessing for $path::$connector {} + impl + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1039,6 +1078,86 @@ default_imp_for_pre_processing_steps!( connector::Zsl ); +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} + +default_imp_for_post_processing_steps!( + connector::Adyenplatform, + connector::Adyen, + connector::Airwallex, + connector::Bankofamerica, + connector::Cybersource, + connector::Gocardless, + connector::Nmi, + connector::Nuvei, + connector::Payme, + connector::Paypal, + connector::Shift4, + connector::Stripe, + connector::Trustpay, + connector::Aci, + connector::Authorizedotnet, + connector::Bambora, + connector::Bamboraapac, + connector::Billwerk, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Coinbase, + connector::Cryptopay, + connector::Datatrans, + connector::Dlocal, + connector::Ebanx, + connector::Iatapay, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Gpayments, + connector::Helcim, + connector::Klarna, + connector::Mifinity, + connector::Mollie, + connector::Multisafepay, + connector::Netcetera, + connector::Nexinets, + connector::Noon, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payone, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Threedsecureio, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen, + connector::Zsl, + connector::Razorpay +); + macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index f4f8409912e..63224f5b0cf 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsApproveRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Approve, @@ -36,9 +37,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 50cf31730a9..db34c40d928 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use common_enums as enums; use router_env::metrics::add_attributes; // use router_env::tracing::Instrument; @@ -16,6 +17,7 @@ use crate::{ services, services::api::ConnectorValidation, types::{self, api, domain, storage, transformers::ForeignFrom}, + utils::OptionExt, }; #[async_trait] @@ -34,6 +36,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::Authorize, @@ -52,9 +55,39 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + let payment_method = &self + .payment_attempt + .payment_method + .get_required_value("PaymentMethod")?; + + let data = if *payment_method == enums::PaymentMethod::OpenBanking { + payments::get_merchant_bank_data_for_open_banking_connectors( + merchant_connector_account, + key_store, + connector, + state, + merchant_account, + ) + .await? + } else { + None + }; + + Ok(data) + } } #[async_trait] impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData { @@ -170,6 +203,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu authorize_preprocessing_steps(state, &self, true, connector).await } + async fn postprocessing_steps<'a>( + self, + state: &SessionState, + connector: &api::ConnectorData, + ) -> RouterResult<Self> { + authorize_postprocessing_steps(state, &self, true, connector).await + } + async fn create_connector_customer<'a>( &self, state: &SessionState, @@ -399,3 +440,53 @@ pub async fn authorize_preprocessing_steps<F: Clone>( Ok(router_data.clone()) } } + +pub async fn authorize_postprocessing_steps<F: Clone>( + state: &SessionState, + router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + confirm: bool, + connector: &api::ConnectorData, +) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> { + if confirm { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let postprocessing_request_data = + types::PaymentsPostProcessingData::try_from(router_data.to_owned())?; + + let postprocessing_response_data: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let postprocessing_router_data = + helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>( + router_data.clone(), + postprocessing_request_data, + postprocessing_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &postprocessing_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + + let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data.request.to_owned(), + resp.response, + ); + + Ok(authorize_router_data) + } else { + Ok(router_data.clone()) + } +} diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index d61730117a8..486e8bb75dc 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -24,6 +24,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCancelRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Void, @@ -36,9 +37,21 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 1c4f76d9833..a7f30f2a41b 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCaptureRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Capture, @@ -36,9 +37,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 6bef7e95859..d3ae67f46c3 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -28,6 +28,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::CompleteAuthorize, @@ -46,9 +47,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index 2aa808f9532..3bc05cedb45 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -27,6 +27,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> { Box::pin(transformers::construct_payment_router_data::< api::IncrementalAuthorization, @@ -39,9 +40,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index d094fe6a21d..cb6c6f50d5e 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { @@ -39,9 +40,21 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index cb1dcd5b19f..501c0a40dab 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsRejectRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Reject, @@ -35,9 +36,21 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 664038454a4..883203ad99e 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -39,6 +39,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Session, @@ -51,9 +52,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &routes::SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 773677f3e7c..0d4648b81f4 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -31,6 +31,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::SetupMandateRouterData> { Box::pin(transformers::construct_payment_router_data::< api::SetupMandate, @@ -43,9 +44,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index da44703732f..1579322995b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -66,8 +66,9 @@ use crate::{ self, enums as storage_enums, ephemeral_key, CardTokenData, CustomerUpdate::Update, }, transformers::{ForeignFrom, ForeignTryFrom}, - AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference, - PaymentsResponseData, RecurringMandatePaymentData, RouterData, + AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse, + MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData, + RecipientIdType, RecurringMandatePaymentData, RouterData, }, utils::{ self, @@ -2429,6 +2430,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, @@ -2503,6 +2505,10 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect ), + api_enums::PaymentMethod::OpenBanking => matches!( + payment_method_type, + api_enums::PaymentMethodType::OpenBankingPIS + ), } } @@ -3341,6 +3347,15 @@ impl MerchantConnectorAccountType { Self::CacheVal(_) => None, } } + + pub fn get_additional_merchant_data( + &self, + ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> { + match self { + Self::DbVal(db_val) => db_val.additional_merchant_data.clone(), + Self::CacheVal(_) => None, + } + } } /// Query for merchant connector account either by business label or profile id @@ -4024,6 +4039,9 @@ pub async fn get_additional_payment_data( api_models::payments::PaymentMethodData::CardToken(_) => { api_models::payments::AdditionalPaymentData::CardToken {} } + api_models::payments::PaymentMethodData::OpenBanking(_) => { + api_models::payments::AdditionalPaymentData::OpenBanking {} + } } } @@ -4572,6 +4590,11 @@ pub fn get_key_params_for_surcharge_details( gift_card.get_payment_method_type(), None, )), + api_models::payments::PaymentMethodData::OpenBanking(ob_data) => Some(( + common_enums::PaymentMethod::OpenBanking, + ob_data.get_payment_method_type(), + None, + )), api_models::payments::PaymentMethodData::CardToken(_) => None, } } @@ -4669,6 +4692,40 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr } } +pub fn get_recipient_id_for_open_banking( + merchant_data: &AdditionalMerchantData, +) -> Result<Option<String>, errors::ApiErrorResponse> { + match merchant_data { + AdditionalMerchantData::OpenBankingRecipientData(data) => match data { + MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())), + MerchantRecipientData::AccountData(acc_data) => match acc_data { + MerchantAccountData::Bacs { + connector_recipient_id, + .. + } => match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), + Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + MerchantAccountData::Iban { + connector_recipient_id, + .. + } => match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), + Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + }, + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + } +} // This function validates the intent fulfillment time expiry set by the merchant in the request pub fn validate_intent_fulfillment_expiry( intent_fulfillment_time: u32, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index a28b9fe3dd2..fc075f29799 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1116,6 +1116,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => { (None, None) } + types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None), types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None), @@ -1338,13 +1339,14 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .in_current_span(), ); - let (payment_intent, _, _) = futures::try_join!( + let (payment_intent, _, payment_attempt) = futures::try_join!( utils::flatten_join_error(payment_intent_fut), utils::flatten_join_error(mandate_update_fut), utils::flatten_join_error(payment_attempt_fut) )?; payment_data.payment_intent = payment_intent; + payment_data.payment_attempt = payment_attempt; router_data.payment_method_status.and_then(|status| { payment_data .payment_method_info diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 6160ffacb0a..bf5ae5aa635 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -306,7 +306,7 @@ where ) .await?; - payments::call_connector_service( + let (router_data, _mca) = payments::call_connector_service( state, req_state, merchant_account, @@ -323,7 +323,9 @@ where business_profile, true, ) - .await + .await?; + + Ok(router_data) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a5648af427c..9f9231b1d4e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -38,6 +38,7 @@ use crate::{ }; #[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, @@ -46,6 +47,7 @@ pub async fn construct_payment_router_data<'a, F, T>( _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -157,7 +159,14 @@ where .payment_attempt .authentication_type .unwrap_or_default(), - connector_meta_data: merchant_connector_account.get_metadata(), + connector_meta_data: if let Some(data) = merchant_recipient_data { + let val = serde_json::to_value(data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encoding MerchantRecipientData")?; + Some(Secret::new(val)) + } else { + merchant_connector_account.get_metadata() + }, connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, @@ -909,7 +918,7 @@ where { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { - payment_attempt + let condition1 = payment_attempt .connector .as_ref() .map(|connector| { @@ -924,7 +933,36 @@ where Some(false) } }) - .unwrap_or(false) + .unwrap_or(false); + + // This condition to be triggered for open banking connectors, third party SDK session token will be provided + let condition2 = payment_attempt + .connector + .as_ref() + .map(|connector| matches!(connector.as_str(), "plaid")) + .and_then(|is_connector_supports_third_party_sdk| { + if is_connector_supports_third_party_sdk { + payment_attempt + .payment_method + .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking)) + .and_then(|first_match| { + payment_attempt + .payment_method_type + .map(|pmt| { + matches!( + pmt, + diesel_models::enums::PaymentMethodType::OpenBankingPIS + ) + }) + .map(|second_match| first_match && second_match) + }) + } else { + Some(false) + } + }) + .unwrap_or(false); + + condition1 || condition2 } else { false } @@ -1297,6 +1335,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .map(|customer| customer.clone().into_inner()) }); + let customer_id = additional_data + .customer_data + .as_ref() + .map(|data| data.customer_id.clone()); + let charges = match payment_data.payment_intent.charges { Some(charges) => charges .peek() @@ -1340,7 +1383,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz router_return_url, webhook_url, complete_authorize_url, - customer_id: None, + customer_id, surcharge_details: payment_data.surcharge_details, request_incremental_authorization: matches!( payment_data diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 0d4c525f104..e91a55e860c 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -329,6 +329,7 @@ pub async fn filter_payout_methods( | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => continue, } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index b5f97a09f70..c5e536de3aa 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -42,9 +42,10 @@ pub use hyperswitch_domain_models::{ DestinationChargeRefund, DirectChargeRefund, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, RefundsData, ResponseId, RetrieveFileRequestData, - SetupMandateRequestData, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, + PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, + RefundsData, ResponseId, RetrieveFileRequestData, SetupMandateRequestData, + SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ @@ -80,6 +81,8 @@ pub type PaymentsAuthorizeRouterData = RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<api::PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; +pub type PaymentsPostProcessingRouterData = + RouterData<api::PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = @@ -163,6 +166,11 @@ pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< PaymentsPreProcessingData, PaymentsResponseData, >; +pub type PaymentsPostProcessingType = dyn services::ConnectorIntegration< + api::PostProcessing, + PaymentsPostProcessingData, + PaymentsResponseData, +>; pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration< api::CompleteAuthorize, CompleteAuthorizeData, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e1dbf452eff..3c1d8175e8b 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -2,10 +2,10 @@ pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate, - PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, - PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, - PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, - PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, + OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, + PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, + PaymentListResponseV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, + PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, @@ -18,14 +18,14 @@ use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, - PreProcessing, Reject, Session, SetupMandate, Void, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, }; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentRejectV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, - PaymentsCompleteAuthorizeV2, PaymentsPreProcessingV2, + PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, }; use crate::{ core::errors, @@ -172,6 +172,15 @@ pub trait PaymentsPreProcessing: { } +pub trait PaymentsPostProcessing: + api::ConnectorIntegration< + PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, +> +{ +} + pub trait Payment: api_types::ConnectorCommon + api_types::ConnectorValidation @@ -187,6 +196,7 @@ pub trait Payment: + PaymentSession + PaymentToken + PaymentsPreProcessing + + PaymentsPostProcessing + ConnectorCustomer + PaymentIncrementalAuthorization { diff --git a/crates/router/src/types/api/payments_v2.rs b/crates/router/src/types/api/payments_v2.rs index fc490ea3d79..639dc0de5bc 100644 --- a/crates/router/src/types/api/payments_v2.rs +++ b/crates/router/src/types/api/payments_v2.rs @@ -3,7 +3,7 @@ use hyperswitch_domain_models::{ router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PreProcessing, Reject, Session, SetupMandate, Void, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, }, }; @@ -152,6 +152,16 @@ pub trait PaymentsPreProcessingV2: { } +pub trait PaymentsPostProcessingV2: + api::ConnectorIntegrationV2< + PostProcessing, + PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, +> +{ +} + pub trait PaymentV2: api_types::ConnectorCommon + api_types::ConnectorValidation @@ -167,6 +177,7 @@ pub trait PaymentV2: + PaymentSessionV2 + PaymentTokenV2 + PaymentsPreProcessingV2 + + PaymentsPostProcessingV2 + ConnectorCustomerV2 + PaymentIncrementalAuthorizationV2 { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 78c2bf231f2..9a42916f68d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -478,6 +478,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBankingPIS | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum @@ -556,6 +557,7 @@ impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), + payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking), payments::PaymentMethodData::MandatePayment => { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("Mandate payments cannot have payment_method_data field".to_string()), diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 3e2708fb1f4..3af6e277de9 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -1,4 +1,5 @@ use api_models::payments::{Address, AddressDetails}; +use common_utils::id_type; use router::types::{self, domain, storage::enums}; use crate::{ @@ -41,6 +42,7 @@ impl CashtocodeTest { payment_method_type: Option<enums::PaymentMethodType>, payment_method_data: domain::PaymentMethodData, ) -> Option<types::PaymentsAuthorizeData> { + let cust_id = id_type::CustomerId::from("John Doe".into()); Some(types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::EUR, @@ -66,7 +68,7 @@ impl CashtocodeTest { router_return_url: Some(String::from("https://google.com")), webhook_url: None, complete_authorize_url: None, - customer_id: Some("John Doe".to_owned()), + customer_id: if let Ok(id) = cust_id { Some(id) } else { None }, surcharge_details: None, request_incremental_authorization: false, metadata: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index b03fee739f7..736c9ae6b53 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -560,6 +560,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, + Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Err(_) => None, } } @@ -1069,6 +1070,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, + Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Err(_) => None, } }
2024-03-04T13:21:57Z
## Description <!-- Describe your changes in detail --> - Added Post-Processing flows for Open banking connectors - Traits and and type changes - #3758 needs to go in first ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Add Plaid MCA with `payment_method` as `open_banking` and `payment_method_type` as `open_banking_pis` ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/connectors' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data-raw '{ "connector_type": "payment_processor", "connector_name": "plaid", "connector_account_details": { "auth_type": "BodyKey", "api_key": "some_key", "key1": "some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "recurring_enabled": false, "installment_payment_enabled": false, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Response - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_gVM5IWhLHFsW5q8F3uez", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "connector_webhook_details": null, "metadata": { "city": "NY", "unit": "246" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": null, "business_label": null, "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ```
926dcd3a3c0f3c09d39767e2a2c5721a42272322
1. Add Plaid MCA with `payment_method` as `open_banking` and `payment_method_type` as `open_banking_pis` ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/connectors' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data-raw '{ "connector_type": "payment_processor", "connector_name": "plaid", "connector_account_details": { "auth_type": "BodyKey", "api_key": "some_key", "key1": "some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "recurring_enabled": false, "installment_payment_enabled": false, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Response - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_gVM5IWhLHFsW5q8F3uez", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "connector_webhook_details": null, "metadata": { "city": "NY", "unit": "246" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": null, "business_label": null, "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ```
[ "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/common_enums/src/transformers.rs", "crates/connector_configs/src/response_modifier.rs", "crates/connector_configs/src/transformer.rs", "crates/euclid/src/dssa/graph.rs", "crates/euclid/src/frontend/ast/lowering.rs", "crat...
juspay/hyperswitch
juspay__hyperswitch-3944
Bug: feat: add caching for roles Currently in authorization, we look at the resource and the role in the JWT to check whether that particular call is valid or not. Upon the introduction of custom roles, this has increased db calls in the authorization phase as we need to get the permissions associated to a particular role. This will have unnecessary load on db and hits the performance of every api call. To fix this, redis needs to be used to cache the permissions for a custom role.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 8f77f72aad5..1641c0ae536 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -128,8 +128,6 @@ pub struct SwitchMerchantIdRequest { pub merchant_id: String, } -pub type SwitchMerchantResponse = DashboardEntryResponse; - #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateInternalUserRequest { pub name: Secret<String>, diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 80d3861969a..411bf823a22 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,8 +1,6 @@ use common_enums::PermissionGroup; use common_utils::pii; -use crate::user::DashboardEntryResponse; - pub mod role; #[derive(Debug, serde::Serialize)] @@ -99,8 +97,6 @@ pub struct AcceptInvitationRequest { pub need_dashboard_entry_response: Option<bool>, } -pub type AcceptInvitationResponse = DashboardEntryResponse; - #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct DeleteUserRoleRequest { pub email: pii::Email, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 72f160990e5..87a16b73a8b 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -78,6 +78,8 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; +pub const ROLE_CACHE_PREFIX: &str = "CR_"; + #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b8b8cbd24c7..fceee528057 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -94,6 +94,7 @@ pub async fn signup( ) .await?; let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, @@ -121,6 +122,7 @@ pub async fn signin_without_invite_checks( let user_role = user_from_db.get_role_from_db(state.clone()).await?; let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, @@ -966,6 +968,8 @@ pub async fn accept_invite_from_email( let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result) + .await; Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response( @@ -1044,7 +1048,7 @@ pub async fn switch_merchant_id( state: AppState, request: user_api::SwitchMerchantIdRequest, user_from_token: auth::UserFromToken, -) -> UserResponse<user_api::SwitchMerchantResponse> { +) -> 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(), @@ -1093,13 +1097,14 @@ pub async fn switch_merchant_id( .organization_id; let token = utils::user::generate_jwt_auth_token_with_custom_role_attributes( - state, + &state, &user, request.merchant_id.clone(), - org_id, + org_id.clone(), user_from_token.role_id.clone(), ) .await?; + (token, user_from_token.role_id) } else { let user_roles = state @@ -1120,11 +1125,13 @@ pub async fn switch_merchant_id( .attach_printable("User doesn't have access to switch")?; let token = utils::user::generate_jwt_auth_token(&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()) }; Ok(ApplicationResponse::Json( - user_api::SwitchMerchantResponse { + user_api::DashboardEntryResponse { token, name: user.get_name(), email: user.get_email(), @@ -1266,6 +1273,7 @@ pub async fn verify_email_without_invite_checks( .await .map_err(|e| logger::error!(?e)); let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 9dca9b43d96..b81b980c07a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -159,6 +159,7 @@ pub async fn transfer_org_ownership( .to_not_found_response(UserErrors::InvalidRoleOperation)?; let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, @@ -169,7 +170,7 @@ pub async fn accept_invitation( state: AppState, user_token: auth::UserWithoutMerchantFromToken, req: user_role_api::AcceptInvitationRequest, -) -> UserResponse<user_role_api::AcceptInvitationResponse> { +) -> UserResponse<user_api::DashboardEntryResponse> { let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { state .store @@ -202,6 +203,8 @@ pub async fn accept_invitation( .into(); let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; + return Ok(ApplicationResponse::Json( utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )); diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 346e563ee32..2ee8302be63 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -17,6 +17,7 @@ use crate::{ use crate::{ core::errors::{UserErrors, UserResult}, routes::AppState, + services::authorization as authz, }; #[cfg(feature = "olap")] @@ -47,10 +48,23 @@ pub async fn insert_role_in_blacklist(state: &AppState, role_id: &str) -> UserRe date_time::now_unix_timestamp(), expiry, ) + .await + .change_context(UserErrors::InternalServerError)?; + invalidate_role_cache(state, role_id) .await .change_context(UserErrors::InternalServerError) } +#[cfg(feature = "olap")] +async fn invalidate_role_cache(state: &AppState, role_id: &str) -> RouterResult<()> { + let redis_conn = get_redis_connection(state)?; + redis_conn + .delete_key(authz::get_cache_key_from_role_id(role_id).as_str()) + .await + .map(|_| ()) + .change_context(ApiErrorResponse::InternalServerError) +} + pub async fn check_user_in_blacklist<A: AppStateInfo>( state: &A, user_id: &str, diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 2a516cc82d5..dc6d82d4e92 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -1,7 +1,13 @@ +use std::sync::Arc; + use common_enums::PermissionGroup; +use error_stack::{IntoReport, ResultExt}; +use redis_interface::RedisConnectionPool; +use router_env::logger; use super::authentication::AuthToken; use crate::{ + consts, core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt}, routes::app::AppStateInfo, }; @@ -19,22 +25,95 @@ pub async fn get_permissions<A>( where A: AppStateInfo + Sync, { - if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { - Ok(get_permissions_from_groups( - role_info.get_permission_groups(), - )) - } else { - state - .store() - .find_role_by_role_id_in_merchant_scope( - &token.role_id, - &token.merchant_id, - &token.org_id, - ) - .await - .map(|role| get_permissions_from_groups(&role.groups)) - .to_not_found_response(ApiErrorResponse::InvalidJwtToken) + if let Some(permissions) = get_permissions_from_predefined_roles(&token.role_id) { + return Ok(permissions); + } + + if let Ok(permissions) = get_permissions_from_cache(state, &token.role_id) + .await + .map_err(|e| logger::error!("Failed to get permissions from cache {}", e)) + { + return Ok(permissions); } + + let permissions = + get_permissions_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?; + + let token_expiry: i64 = token + .exp + .try_into() + .into_report() + .change_context(ApiErrorResponse::InternalServerError)?; + let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); + + set_permissions_in_cache(state, &token.role_id, &permissions, cache_ttl) + .await + .map_err(|e| logger::error!("Failed to set permissions in cache {}", e)) + .ok(); + Ok(permissions) +} + +async fn get_permissions_from_cache<A>( + state: &A, + role_id: &str, +) -> RouterResult<Vec<permissions::Permission>> +where + A: AppStateInfo + Sync, +{ + let redis_conn = get_redis_connection(state)?; + + redis_conn + .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "Vec<Permission>") + .await + .change_context(ApiErrorResponse::InternalServerError) +} + +pub fn get_cache_key_from_role_id(role_id: &str) -> String { + format!("{}{}", consts::ROLE_CACHE_PREFIX, role_id) +} + +fn get_permissions_from_predefined_roles(role_id: &str) -> Option<Vec<permissions::Permission>> { + roles::predefined_roles::PREDEFINED_ROLES + .get(role_id) + .map(|role_info| get_permissions_from_groups(role_info.get_permission_groups())) +} + +async fn get_permissions_from_db<A>( + state: &A, + role_id: &str, + merchant_id: &str, + org_id: &str, +) -> RouterResult<Vec<permissions::Permission>> +where + A: AppStateInfo + Sync, +{ + state + .store() + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .await + .map(|role| get_permissions_from_groups(&role.groups)) + .to_not_found_response(ApiErrorResponse::InvalidJwtToken) +} + +pub async fn set_permissions_in_cache<A>( + state: &A, + role_id: &str, + permissions: &Vec<permissions::Permission>, + expiry: i64, +) -> RouterResult<()> +where + A: AppStateInfo + Sync, +{ + let redis_conn = get_redis_connection(state)?; + + redis_conn + .serialize_and_set_key_with_expiry( + &get_cache_key_from_role_id(role_id), + permissions, + expiry, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) } pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> { @@ -62,3 +141,11 @@ pub fn check_authorization( .into(), ) } + +fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { + state + .store() + .get_redis_conn() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection") +} diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index d6a20b7f8ed..7b82e84d64c 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -187,7 +187,7 @@ fn get_group_description(group: PermissionGroup) -> &'static str { "View Payments, Refunds, Mandates, Disputes and Customers" } PermissionGroup::OperationsManage => { - "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers" + "Create, modify and delete Payments, Refunds, Mandates, Disputes and Customers" } PermissionGroup::ConnectorsView => { "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details" diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 8d436618b32..edf9a40915c 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,6 +1,8 @@ use strum::Display; -#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)] +#[derive( + PartialEq, Display, Clone, Debug, Copy, Eq, Hash, serde::Deserialize, serde::Serialize, +)] pub enum Permission { PaymentRead, PaymentWrite, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d6e878456e8..1850eb4b81a 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -861,8 +861,11 @@ impl SignInWithSingleRoleStrategy { async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> { let token = utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await; + let dashboard_entry_response = utils::user::get_dashboard_entry_response(state, self.user, self.user_role, token)?; + Ok(user_api::SignInResponse::DashboardEntry( dashboard_entry_response, )) diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index c3b795d1a57..cfab331f148 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -87,7 +87,7 @@ pub async fn generate_jwt_auth_token( } pub async fn generate_jwt_auth_token_with_custom_role_attributes( - state: AppState, + state: &AppState, user: &UserFromStorage, merchant_id: String, org_id: String, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index bb83b82f2da..a0ac1400582 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,11 +1,14 @@ use api_models::user_role as user_role_api; use common_enums::PermissionGroup; -use error_stack::ResultExt; +use diesel_models::user_role::UserRole; +use error_stack::{IntoReport, ResultExt}; +use router_env::logger; use crate::{ + consts, core::errors::{UserErrors, UserResult}, routes::AppState, - services::authorization::{permissions::Permission, roles}, + services::authorization::{self as authz, permissions::Permission, roles}, types::domain, }; @@ -83,3 +86,47 @@ pub async fn validate_role_name( Ok(()) } + +pub async fn set_role_permissions_in_cache_by_user_role( + state: &AppState, + user_role: &UserRole, +) -> bool { + set_role_permissions_in_cache_if_required( + state, + user_role.role_id.as_str(), + user_role.merchant_id.as_str(), + user_role.org_id.as_str(), + ) + .await + .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) + .is_ok() +} + +pub async fn set_role_permissions_in_cache_if_required( + state: &AppState, + role_id: &str, + merchant_id: &str, + org_id: &str, +) -> UserResult<()> { + if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) { + return Ok(()); + } + + let role_info = roles::RoleInfo::from_role_id(state, role_id, merchant_id, org_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error getting role_info from role_id")?; + + authz::set_permissions_in_cache( + state, + role_id, + &role_info.get_permissions_set().into_iter().collect(), + consts::JWT_TOKEN_TIME_IN_SECS + .try_into() + .into_report() + .change_context(UserErrors::InternalServerError)?, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error setting permissions in redis") +}
2024-03-04T13:11:08Z
## Description <!-- Describe your changes in detail --> This PR will add caching for custom roles to reduce db calls and improve efficiency. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3944 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman. This cannot be tested in hosted environment as redis is not accessible directly but can be tested in local environment. So, writing the instructions for local testing here. 1. Signin with a user who has assigned a custom role (not a predefined role) ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email", "password": "password" }' ``` You will get the following response ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWQyOTQzMDgtYjhjMC00ZTU1LTkwYjgtMjA5ZGZkNjFhZWE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA5MTI1MjczIiwicm9sZV9pZCI6InJvbGVfTmRDVW12WUIwalhCRmpwUW8ydEUiLCJleHAiOjE3MDk3MjkwNzcsIm9yZ19pZCI6Im9yZ181UEluV2RTN2FJc0FGa3g5dFUxWCJ9.Cf7ascQFk6-1USmhJlkk-B9gu0v6qQ-07SXCjZw6wEU", "merchant_id": "merchant_1709125273", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "role_NdCUmvYB0jXBFjpQo2tE" } ``` Notice that `user_role` has a `role_id` which starts with `role_`. That means this user has been assigned a custom role. 2. Now run `redis_cli` command in the terminal. 3. In the prompt, execute `keys *` command. You should get the output that looks like this ``` 1) "CR_role_NdCUmvYB0jXBFjpQo2tE" 2) "123" 3) "accounts" 4) "234" ``` Notice that there is a key that starts with `CR_` and the remaining part matches with the `role_id` that we got in the signin response.
f132527490a7d8cd8469573d8e6856f33974959f
Postman. This cannot be tested in hosted environment as redis is not accessible directly but can be tested in local environment. So, writing the instructions for local testing here. 1. Signin with a user who has assigned a custom role (not a predefined role) ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email", "password": "password" }' ``` You will get the following response ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWQyOTQzMDgtYjhjMC00ZTU1LTkwYjgtMjA5ZGZkNjFhZWE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA5MTI1MjczIiwicm9sZV9pZCI6InJvbGVfTmRDVW12WUIwalhCRmpwUW8ydEUiLCJleHAiOjE3MDk3MjkwNzcsIm9yZ19pZCI6Im9yZ181UEluV2RTN2FJc0FGa3g5dFUxWCJ9.Cf7ascQFk6-1USmhJlkk-B9gu0v6qQ-07SXCjZw6wEU", "merchant_id": "merchant_1709125273", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "role_NdCUmvYB0jXBFjpQo2tE" } ``` Notice that `user_role` has a `role_id` which starts with `role_`. That means this user has been assigned a custom role. 2. Now run `redis_cli` command in the terminal. 3. In the prompt, execute `keys *` command. You should get the output that looks like this ``` 1) "CR_role_NdCUmvYB0jXBFjpQo2tE" 2) "123" 3) "accounts" 4) "234" ``` Notice that there is a key that starts with `CR_` and the remaining part matches with the `role_id` that we got in the signin response.
[ "crates/api_models/src/user.rs", "crates/api_models/src/user_role.rs", "crates/router/src/consts.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/services/authentication/blacklist.rs", "crates/router/src/services/authorization.rs", "crates/router/src/ser...
juspay/hyperswitch
juspay__hyperswitch-3943
Bug: Use mget to check in Blocklist Kv Use MGet to check whether check multiple values in blocklist.
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 346e563ee32..3a386c7793c 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -66,19 +66,25 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>( .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) } -pub async fn check_role_in_blacklist<A: AppStateInfo>( +pub async fn check_user_and_role_in_blacklist<A: AppStateInfo>( state: &A, + user_id: &str, role_id: &str, token_expiry: u64, ) -> RouterResult<bool> { - let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); + let user_token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); + let role_token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; - redis_conn - .get_key::<Option<i64>>(token.as_str()) + + Ok(redis_conn + .get_multiple_keys::<Vec<&str>, i64>(vec![user_token.as_str(), role_token.as_str()]) .await - .change_context(ApiErrorResponse::InternalServerError) - .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) + .change_context(ApiErrorResponse::InternalServerError)? + .into_iter() + .max() + .flatten() + .map_or(false, |timestamp| timestamp > token_issued_at)) } #[cfg(feature = "email")] @@ -136,10 +142,7 @@ impl BlackList for AuthToken { where A: AppStateInfo + Sync, { - Ok( - check_user_in_blacklist(state, &self.user_id, self.exp).await? - || check_role_in_blacklist(state, &self.role_id, self.exp).await?, - ) + check_user_and_role_in_blacklist(state, &self.user_id, &self.role_id, self.exp).await } }
2024-03-04T13:00:49Z
## Description Use MGet to check whether role or user is blacklisted in KV. Instead of checking user and role separately, MGet can help to do it in one call. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Enhancement ## How did you test it? Singup --> Sigin --> Create a new role --> Invite new user with newly created role --> Sign In new user --> perform some operations which the user with assigned role can perform --> now update the role --> try performing same operation for the newly invited user. It won't be valid since role has been blocklist. Can also check KV for blocklisted role_id and user_id. Curls for singup/singin curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test121@juspay.in", "password": "Test@12", "country": "IN" } ' curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test12345@juspay.in", "password": "260e5c5c-dc96-4cb9-870c-eb18ab8ab577" }' Create Role: curl --location 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test", "groups": ["operations_view", "operations_manage"], "role_scope": "organization" }' Update Role: curl --location --request PUT 'http://localhost:8080/user/role/role_QvY913dYo2b05D64bJ8l' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "groups": ["operations_view"] }'
f132527490a7d8cd8469573d8e6856f33974959f
Singup --> Sigin --> Create a new role --> Invite new user with newly created role --> Sign In new user --> perform some operations which the user with assigned role can perform --> now update the role --> try performing same operation for the newly invited user. It won't be valid since role has been blocklist. Can also check KV for blocklisted role_id and user_id. Curls for singup/singin curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test121@juspay.in", "password": "Test@12", "country": "IN" } ' curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test12345@juspay.in", "password": "260e5c5c-dc96-4cb9-870c-eb18ab8ab577" }' Create Role: curl --location 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test", "groups": ["operations_view", "operations_manage"], "role_scope": "organization" }' Update Role: curl --location --request PUT 'http://localhost:8080/user/role/role_QvY913dYo2b05D64bJ8l' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data '{ "groups": ["operations_view"] }'
[ "crates/router/src/services/authentication/blacklist.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3937
Bug: [FEATURE] : [Coinbase][Cryptopay] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index 5b3b6f63278..f02984136bd 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -21,7 +21,7 @@ pub struct LocalPrice { #[derive(Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct Metadata { pub customer_id: Option<String>, - pub customer_name: Option<String>, + pub customer_name: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -335,7 +335,7 @@ pub enum WebhookEventType { pub struct CoinbasePaymentResponseData { pub id: String, pub code: String, - pub name: Option<String>, + pub name: Option<Secret<String>>, pub utxo: bool, pub pricing: HashMap<String, OverpaymentAbsoluteThreshold>, pub fee_rate: f64, @@ -355,7 +355,7 @@ pub struct CoinbasePaymentResponseData { pub fees_settled: bool, pub pricing_type: String, pub redirect_url: String, - pub support_email: String, + pub support_email: pii::Email, pub brand_logo_url: String, pub offchain_eligible: bool, pub organization_name: String, diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index d4697e3ba14..635d4a66c26 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -222,7 +222,7 @@ pub struct CryptopayPaymentResponseData { pub customer_id: Option<String>, pub status: CryptopayPaymentStatus, pub status_context: Option<String>, - pub address: Option<String>, + pub address: Option<Secret<String>>, pub network: Option<String>, pub uri: Option<String>, pub price_amount: Option<String>,
2024-03-04T10:45:14Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for coinbase and cryptopay. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a crypto payment with coinbase _Note:Metadata not passed in dashboard_ Metadata to be included in Connector Create ``` "metadata": { "pricing_type": "fixed_price" }, ``` ``` { "amount": 200, "currency": "GBP", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", // "setup_future_usage": "off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": false, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": { "pay_currency": "USD" } } } ``` 2. Create a payment in Cryptopay ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_JsfXOsrNjUW5OCAb7RKI6Fzg1XlF8ajI48gr2AVcgxnGnqp2Cvv4WnFY8RWPTIhD' \ --data-raw '{ "amount": 200, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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" } }, "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,application/signed-exchange;v=b3", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": false, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": { "pay_currency": "XRP" } } }' ``` 4. Check if pii data in `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Coinbase Response ``` masked_response\":\"{\\\"data\\\":{\\\"id\\\":\\\"b74480cf-c92d-44b2-af40-5a6a91a7f910\\\",\\\"code\\\":\\\"GZ62GFRC\\\",\\\"name\\\":null,\\\"utxo\\\":false,\\\"pricing\\\":{\\\"polygon\\\":{\\\"amount\\\":\\\"226.804602000\\\",\\\"currency\\\":\\\"PMATIC\\\"},\\\"bitcoin\\\":{\\\"amount\\\":\\\"0.00385362\\\",\\\"currency\\\":\\\"BTC\\\"},\\\"bitcoincash\\\":{\\\"amount\\\":\\\"0.63153123\\\",\\\"currency\\\":\\\"BCH\\\"},\\\"usdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"USDC\\\"},\\\"pweth\\\":{\\\"amount\\\":\\\"0.067417426548866693\\\",\\\"currency\\\":\\\"PWETH\\\"},\\\"pusdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"PUSDC\\\"},\\\"apecoin\\\":{\\\"amount\\\":\\\"115.899990075346566553\\\",\\\"currency\\\":\\\"APE\\\"},\\\"tether\\\":{\\\"amount\\\":\\\"254.612571\\\",\\\"currency\\\":\\\"USDT\\\"},\\\"dogecoin\\\":{\\\"amount\\\":\\\"1690.60888278\\\",\\\"currency\\\":\\\"DOGE\\\"},\\\"local\\\":{\\\"amount\\\":\\\"200.00\\\",\\\"currency\\\":\\\"GBP\\\"},\\\"dai\\\":{\\\"amount\\\":\\\"254.728437456192508876\\\",\\\"currency\\\":\\\"DAI\\\"},\\\"polusdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"POLUSDC\\\"},\\\"ethereum\\\":{\\\"amount\\\":\\\"0.067372000\\\",\\\"currency\\\":\\\"ETH\\\"},\\\"shibainu\\\":{\\\"amount\\\":\\\"8225100.216068919102212175\\\",\\\"currency\\\":\\\"SHIB\\\"},\\\"litecoin\\\":{\\\"amount\\\":\\\"3.00803387\\\",\\\"currency\\\":\\\"LTC\\\"}},\\\"fee_rate\\\":0.01,\\\"logo_url\\\":\\\"\\\",\\\"metadata\\\":{\\\"customer_id\\\":null,\\\"customer_name\\\":null},\\\"payments\\\":[],\\\"resource\\\":\\\"charge\\\",\\\"timeline\\\":[{\\\"status\\\":\\\"NEW\\\",\\\"context\\\":null,\\\"time\\\":\\\"2024-03-07T07:33:35Z\\\",\\\"payment\\\":null}],\\\"pwcb_only\\\":false,\\\"cancel_url\\\":\\\"http://localhost:8080/payments/pay_wCjb90F5sNJD1qlvfxAs/merchant_1709796607/redirect/response/coinbase\\\",\\\"created_at\\\":\\\"2024-03-07T07:33:35Z\\\",\\\"expires_at\\\":\\\"2024-03-07T08:33:35Z\\\",\\\"hosted_url\\\":\\\"https://commerce.coinbase.com/charges/GZ62GFRC\\\",\\\"brand_color\\\":\\\"#122332\\\",\\\"description\\\":\\\"Its my first payment request\\\",\\\"confirmed_at\\\":null,\\\"fees_settled\\\":true,\\\"pricing_type\\\":\\\"fixed_price\\\",\\\"redirect_url\\\":\\\"http://localhost:8080/payments/pay_wCjb90F5sNJD1qlvfxAs/merchant_1709796607/redirect/response/coinbase\\\",\\\"support_email\\\":\\\\"********@gmail.com\\\",\\\"brand_logo_url\\\":\\\"\\\",\\\"offchain_eligible\\\":false,\\\"organization_name\\\":\\\"\\\",\\\"payment_threshold\\\":{\\\"overpayment_absolute_threshold\\\":{\\\"amount\\\":\\\"5.00\\\",\\\"currency\\\":\\\"USD\\\"},\\\"overpayment_relative_threshold\\\":\\\"0.005\\\",\\\"underpayment_absolute_threshold\\\":{\\\"amount\\\":\\\"5.00\\\",\\\"currency\\\":\\\"USD\\\"},\\\"underpayment_relative_threshold\\\":\\\"0.005\\\"},\\\"coinbase_managed_merchant\\\":false}} ``` Cryptopay Response ``` masked_response\":\"{\\\"data\\\":{\\\"id\\\":\\\"5b837b10-6595-4e19-9ad8-188a17392c0e\\\",\\\"custom_id\\\":\\\"pay_uikX1Kbhlpvo06b0qJk1_1\\\",\\\"customer_id\\\":null,\\\"status\\\":\\\"new\\\",\\\"status_context\\\":null,\\\"address\\\":\\\"*** alloc::string::String ***\\\",\\\"network\\\":\\\"ripple\\\",\\\"uri\\\":\\\"ripple:rfCb49HbVfBLtoeec99APnYfKYu2uLoF35?amount=0.03804&dt=1273215618\\\",\\\"price_amount\\\":\\\"2.0\\\",\\\"price_currency\\\":\\\"INR\\\",\\\"pay_amount\\\":\\\"0.03804\\\",\\\"pay_currency\\\":\\\"XRP\\\",\\\"fee\\\":\\\"0.02\\\",\\\"fee_currency\\\":\\\"INR\\\",\\\"paid_amount\\\":\\\"0.0\\\",\\\"name\\\":null,\\\"description\\\":null,\\\"success_redirect_url\\\":\\\"http://localhost:8080/payments/pay_uikX1Kbhlpvo06b0qJk1/merchant_1709796432/redirect/response/cryptopay\\\",\\\"unsuccess_redirect_url\\\":\\\"http://localhost:8080/payments/pay_uikX1Kbhlpvo06b0qJk1/merchant_1709796432/redirect/response/cryptopay\\\",\\\"hosted_page_url\\\":\\\"https://hosted-business-sandbox.cryptopay.me/invoices/5b837b10-6595-4e19-9ad8-188a17392c0e\\\",\\\"created_at\\\":\\\"2024-03-07T07:27:27+00:00\\\",\\\"expires_at\\\":\\\"2024-03-07T07:37:27+00:00\\\"}} ```
8c103c0f8e838a899a0c1207c88fa7617b37f138
[ "crates/router/src/connector/coinbase/transformers.rs", "crates/router/src/connector/cryptopay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3934
Bug: [FEATURE] : [Worldline][Worldpay][Zen] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index a96a87f05c8..94c60eba3cf 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -27,6 +27,7 @@ pub trait SerializableSecret: Serialize {} impl SerializableSecret for Value {} impl SerializableSecret for u8 {} impl SerializableSecret for u16 {} +impl SerializableSecret for i8 {} impl SerializableSecret for i32 {} impl<'de, T, I> Deserialize<'de> for Secret<T, I> diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 996e06adfc4..1765bb3eeae 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -813,6 +813,8 @@ pub trait CardData { fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>; + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>; + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; } impl CardData for api::Card { @@ -870,6 +872,24 @@ impl CardData for api::Card { let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { + self.card_exp_month + .peek() + .clone() + .parse::<i8>() + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { + self.card_exp_year + .peek() + .clone() + .parse::<i32>() + .into_report() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } } #[track_caller] diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 1eb22fc52d2..7a9a43eedc6 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -95,11 +95,11 @@ pub struct Name { pub struct Shipping { pub city: Option<String>, pub country_code: Option<api_enums::CountryAlpha2>, - pub house_number: Option<String>, + pub house_number: Option<Secret<String>>, pub name: Option<Name>, pub state: Option<Secret<String>>, pub state_code: Option<String>, - pub street: Option<String>, + pub street: Option<Secret<String>>, pub zip: Option<Secret<String>>, } diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index 5d6fdeb5106..5fb5d75d940 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -6,15 +6,15 @@ pub struct BillingAddress { #[serde(skip_serializing_if = "Option::is_none")] pub city: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub address2: Option<String>, - pub postal_code: String, + pub address2: Option<Secret<String>>, + pub postal_code: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub address3: Option<String>, - pub country_code: String, + pub address3: Option<Secret<String>>, + pub country_code: common_enums::CountryAlpha2, #[serde(skip_serializing_if = "Option::is_none")] - pub address1: Option<String>, + pub address1: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -57,7 +57,7 @@ pub enum CustomerAuthentication { #[serde(rename_all = "camelCase")] pub struct ThreeDS { #[serde(skip_serializing_if = "Option::is_none")] - pub authentication_value: Option<String>, + pub authentication_value: Option<Secret<String>>, pub version: ThreeDSVersion, #[serde(skip_serializing_if = "Option::is_none")] pub transaction_id: Option<String>, @@ -93,7 +93,7 @@ pub enum CustomerAuthType { pub struct NetworkToken { #[serde(rename = "type")] pub auth_type: CustomerAuthType, - pub authentication_value: String, + pub authentication_value: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub eci: Option<String>, } @@ -146,7 +146,7 @@ pub struct CardPayment { #[serde(skip_serializing_if = "Option::is_none")] pub billing_address: Option<BillingAddress>, #[serde(skip_serializing_if = "Option::is_none")] - pub card_holder_name: Option<String>, + pub card_holder_name: Option<Secret<String>>, pub card_expiry_date: CardExpiryDate, #[serde(skip_serializing_if = "Option::is_none")] pub cvc: Option<Secret<String>>, @@ -168,15 +168,15 @@ pub struct CardToken { pub struct WalletPayment { #[serde(rename = "type")] pub payment_type: PaymentType, - pub wallet_token: String, + pub wallet_token: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub billing_address: Option<BillingAddress>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct CardExpiryDate { - pub month: i8, - pub year: i32, + pub month: Secret<i8>, + pub year: Secret<i32>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -198,9 +198,9 @@ pub struct Merchant { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFacilitator { - pub pf_id: String, + pub pf_id: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub iso_id: Option<String>, + pub iso_id: Option<Secret<String>>, pub sub_merchant: SubMerchant, } @@ -208,13 +208,13 @@ pub struct PaymentFacilitator { #[serde(rename_all = "camelCase")] pub struct SubMerchant { pub city: String, - pub name: String, + pub name: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<String>, - pub postal_code: String, - pub merchant_id: String, + pub postal_code: Secret<String>, + pub merchant_id: Secret<String>, pub country_code: String, - pub street: String, + pub street: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub tax_id: Option<String>, } diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs index e51b716acf6..0a50885d28e 100644 --- a/crates/router/src/connector/worldpay/response.rs +++ b/crates/router/src/connector/worldpay/response.rs @@ -1,3 +1,4 @@ +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{core::errors, types}; @@ -124,12 +125,14 @@ impl Exemption { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Issuer { - pub authorization_code: String, + pub authorization_code: Secret<String>, } impl Issuer { - pub fn new(authorization_code: String) -> Self { - Self { authorization_code } + pub fn new(code: String) -> Self { + Self { + authorization_code: Secret::new(code), + } } } @@ -187,9 +190,9 @@ impl PaymentInstrumentCard { #[serde(rename_all = "camelCase")] pub struct PaymentInstrumentCardExpiryDate { #[serde(skip_serializing_if = "Option::is_none")] - pub month: Option<i32>, + pub month: Option<Secret<i32>>, #[serde(skip_serializing_if = "Option::is_none")] - pub year: Option<i32>, + pub year: Option<Secret<i32>>, } impl PaymentInstrumentCardExpiryDate { diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 6979502842f..dd92984eb99 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -1,7 +1,6 @@ use base64::Engine; use common_utils::errors::CustomResult; use diesel_models::enums; -use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::Serialize; @@ -47,20 +46,8 @@ fn fetch_payment_instrument( match payment_method { api::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment { card_expiry_date: CardExpiryDate { - month: card - .card_exp_month - .peek() - .clone() - .parse::<i8>() - .into_report() - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, - year: card - .card_exp_year - .peek() - .clone() - .parse::<i32>() - .into_report() - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, + month: utils::CardData::get_expiry_month_as_i8(&card)?, + year: utils::CardData::get_expiry_year_as_i32(&card)?, }, card_number: card.card_number, ..CardPayment::default() @@ -69,14 +56,14 @@ fn fetch_payment_instrument( api_models::payments::WalletData::GooglePay(data) => { Ok(PaymentInstrument::Googlepay(WalletPayment { payment_type: PaymentType::Googlepay, - wallet_token: data.tokenization_data.token, + wallet_token: Secret::new(data.tokenization_data.token), ..WalletPayment::default() })) } api_models::payments::WalletData::ApplePay(data) => { Ok(PaymentInstrument::Applepay(WalletPayment { payment_type: PaymentType::Applepay, - wallet_token: data.payment_data, + wallet_token: Secret::new(data.payment_data), ..WalletPayment::default() })) } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index ebea61304a1..b01b3f027a0 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -2,7 +2,7 @@ use api_models::payments::Card; use cards::CardNumber; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use ring::digest; use serde::{Deserialize, Serialize}; use strum::Display; @@ -200,8 +200,8 @@ pub struct SessionObject { #[derive(Debug, Serialize, Deserialize)] pub struct WalletSessionData { - pub terminal_uuid: Option<String>, - pub pay_wall_secret: Option<String>, + pub terminal_uuid: Option<Secret<String>>, + pub pay_wall_secret: Option<Secret<String>>, } impl TryFrom<(&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card)> for ZenPaymentsRequest { @@ -513,7 +513,8 @@ impl let terminal_uuid = session_data .terminal_uuid .clone() - .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .expose(); let mut checkout_request = CheckoutRequest { merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), specified_payment_channel, @@ -540,7 +541,7 @@ fn get_checkout_signature( .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; let mut signature_data = get_signature_data(checkout_request)?; - signature_data.push_str(&pay_wall_secret); + signature_data.push_str(&pay_wall_secret.expose()); let payload_digest = digest::digest(&digest::SHA256, signature_data.as_bytes()); let mut signature = hex::encode(payload_digest); signature.push_str(";sha256");
2024-03-04T09:40:32Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Worldline, Worldpay and zen. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> _Note: Zen Googlepay and Worldpay can't be tested in sandbox_ 1. Create a card payment with worldpay 2. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` request\":\"{\\\"cardPaymentMethodSpecificInput\\\":{\\\"card\\\":{\\\"cardNumber\\\":\\\"456735**********\\\",\\\"cardholderName\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\",\\\"expiryDate\\\":\\\"*** alloc::string::String ***\\\"},\\\"requiresApproval\\\":false,\\\"paymentProductId\\\":1},\\\"order\\\":{\\\"amountOfMoney\\\":{\\\"amount\\\":20000,\\\"currencyCode\\\":\\\"PLN\\\"},\\\"customer\\\":{\\\"billingAddress\\\":{\\\"city\\\":\\\"San Fransico\\\",\\\"countryCode\\\":\\\"US\\\",\\\"houseNumber\\\":null,\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"stateCode\\\":null,\\\"street\\\":null,\\\"zip\\\":\\\"*** alloc::string::String ***\\\"},\\\"contactDetails\\\":{\\\"emailAddress\\\":\\\"*********@gmail.com\\\",\\\"mobilePhoneNumber\\\":null}},\\\"references\\\":{\\\"merchantReference\\\":\\\"pay_Cm4XoGAkTeXdAaAx3OUo_1\\\"}},\\\"shipping\\\":{\\\"city\\\":\\\"San Fransico\\\",\\\"countryCode\\\":\\\"US\\\",\\\"houseNumber\\\":null,\\\"name\\\":{\\\"firstName\\\":\\\"*** alloc::string::String ***\\\",\\\"surname\\\":\\\"*** alloc::string::String ***\\\",\\\"surnamePrefix\\\":null,\\\"title\\\":null},\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"stateCode\\\":null,\\\"street\\\":null,\\\"zip\\\":\\\"*** alloc::string::String ***\\\"}}\",\"masked_response\":\"{\\\"payment\\\":{\\\"id\\\":\\\"000000113200000139460000100001\\\",\\\"status\\\":\\\"CAPTURE_REQUESTED\\\",\\\"capture_method\\\":\\\"automatic\\\"}, ```
ac8ddd40208f3da5f65ca97bf5033cea5ca3ebe3
[ "crates/masking/src/serde.rs", "crates/router/src/connector/utils.rs", "crates/router/src/connector/worldline/transformers.rs", "crates/router/src/connector/worldpay/requests.rs", "crates/router/src/connector/worldpay/response.rs", "crates/router/src/connector/worldpay/transformers.rs", "crates/router/s...
juspay/hyperswitch
juspay__hyperswitch-3933
Bug: [FEATURE] : [Trustpay][Volt] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 71286bda3f1..d5b65bb9975 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -6,7 +6,7 @@ use common_utils::{ pii::{self, Email}, }; use error_stack::{report, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -1069,8 +1069,8 @@ pub struct GooglePayTransactionInfo { #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayMerchantInfo { - pub merchant_name: String, - pub merchant_id: String, + pub merchant_name: Secret<String>, + pub merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] @@ -1086,7 +1086,7 @@ pub struct GooglePayAllowedPaymentMethods { #[serde(rename_all = "camelCase")] pub struct GpayTokenParameters { pub gateway: String, - pub gateway_merchant_id: String, + pub gateway_merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] @@ -1291,8 +1291,8 @@ impl From<GooglePayTransactionInfo> for api_models::payments::GpayTransactionInf impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo { fn from(value: GooglePayMerchantInfo) -> Self { Self { - merchant_id: Some(value.merchant_id), - merchant_name: value.merchant_name, + merchant_id: Some(value.merchant_id.expose()), + merchant_name: value.merchant_name.expose(), } } } @@ -1329,7 +1329,7 @@ impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters { fn from(value: GpayTokenParameters) -> Self { Self { gateway: value.gateway, - gateway_merchant_id: Some(value.gateway_merchant_id), + gateway_merchant_id: Some(value.gateway_merchant_id.expose()), stripe_version: None, stripe_publishable_key: None, } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index ccb482d5b7c..8e63f5d6ef1 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -190,7 +190,7 @@ pub struct VoltAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, - pub refresh_token: String, + pub refresh_token: Secret<String>, } impl<F, T> TryFrom<types::ResponseRouterData<F, VoltAuthUpdateResponse, T, types::AccessToken>>
2024-03-04T09:30:38Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Trustpay, Volt and Wise. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a Gpay payment with trustpay Generate toke from : https://jsfiddle.net/1agu74ve/1/ ``` const tokenizationSpecification = {   type: 'PAYMENT_GATEWAY',   parameters: {   "gateway": "trustpay", "gatewayMerchantId": "{{merchant_id}}"   } }; ``` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{}}' \ --data-raw '{ "amount": 1800, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Visa •••• 1111", "info": { "card_network": "VISA", "card_details": "1111" }, "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{{token}}" } } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "Dubai", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "count_tickets": 1, "transaction_number": "5590043" } }' ``` 2. Refresh Token flow of volt _Note: can't be tested not implemented_ 3. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response of Trustpay Gpay ``` "masked_response\":\"{\\\"secrets\\\":{\\\"display\\\":\\\"*** alloc::string::String ***\\\",\\\"payment\\\":\\\"*** alloc::string::String ***\\\"},\\\"googleInitResultData\\\":{\\\"merchantInfo\\\":{\\\"merchantName\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\"},\\\"allowedPaymentMethods\\\":[{\\\"type\\\":\\\"CARD\\\",\\\"parameters\\\":{\\\"allowedAuthMethods\\\":[\\\"PAN_ONLY\\\",\\\"CRYPTOGRAM_3DS\\\"],\\\"allowedCardNetworks\\\":[\\\"MASTERCARD\\\",\\\"VISA\\\"]},\\\"tokenizationSpecification\\\":{\\\"type\\\":\\\"PAYMENT_GATEWAY\\\",\\\"parameters\\\":{\\\"gateway\\\":\\\"trustpay\\\",\\\"gatewayMerchantId\\\":\\\"*** alloc::string::String ***\\\"}}}],\\\"transactionInfo\\\":{\\\"countryCode\\\":\\\"IN\\\",\\\"currencyCode\\\":\\\"USD\\\",\\\"totalPriceStatus\\\":\\\"FINAL\\\",\\\"totalPrice\\\":\\\"18.00\\\"}} ```
f132527490a7d8cd8469573d8e6856f33974959f
[ "crates/router/src/connector/trustpay/transformers.rs", "crates/router/src/connector/volt/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3931
Bug: [FEATURE] :[Prophetpay][Rapyd][Shift4][Square] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields into a secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs index b3b641b6d24..563438203d8 100644 --- a/crates/router/src/connector/prophetpay/transformers.rs +++ b/crates/router/src/connector/prophetpay/transformers.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use common_utils::{consts, errors::CustomResult}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; @@ -172,7 +172,7 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>> #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayTokenResponse { - hosted_tokenize_id: String, + hosted_tokenize_id: Secret<String>, } impl<F> @@ -197,7 +197,7 @@ impl<F> let url_data = format!( "{}{}", consts::PROPHETPAY_REDIRECT_URL, - item.response.hosted_tokenize_id + item.response.hosted_tokenize_id.expose() ); let redirect_url = Url::parse(url_data.as_str()) @@ -257,7 +257,7 @@ pub struct ProphetpayCompleteRequest { inquiry_reference: String, profile: Secret<String>, action_type: i8, - card_token: String, + card_token: Secret<String>, } impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>> @@ -268,7 +268,9 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>> item: &ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?; - let card_token = get_card_token(item.router_data.request.redirect_response.clone())?; + let card_token = Secret::new(get_card_token( + item.router_data.request.redirect_response.clone(), + )?); Ok(Self { amount: item.amount.to_owned(), ref_info: item.router_data.connector_request_reference_id.to_owned(), diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 9fd664748e3..bd50a95d8b9 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -87,7 +87,7 @@ pub struct Address { city: Option<String>, state: Option<Secret<String>>, country: Option<String>, - zip: Option<String>, + zip: Option<Secret<String>>, phone_number: Option<Secret<String>>, } @@ -96,7 +96,7 @@ pub struct RapydWallet { #[serde(rename = "type")] payment_type: String, #[serde(rename = "details")] - token: Option<String>, + token: Option<Secret<String>>, } impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest { @@ -145,11 +145,11 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay let digital_wallet = match wallet_data { api_models::payments::WalletData::GooglePay(data) => Some(RapydWallet { payment_type: "google_pay".to_string(), - token: Some(data.tokenization_data.token.to_owned()), + token: Some(Secret::new(data.tokenization_data.token.to_owned())), }), api_models::payments::WalletData::ApplePay(data) => Some(RapydWallet { payment_type: "apple_pay".to_string(), - token: Some(data.payment_data.to_string()), + token: Some(Secret::new(data.payment_data.to_string())), }), _ => None, }; @@ -418,7 +418,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> #[derive(Debug, Serialize, Clone)] pub struct CaptureRequest { amount: Option<i64>, - receipt_email: Option<String>, + receipt_email: Option<Secret<String>>, statement_descriptor: Option<String>, } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 97c19c49af8..4dc2cd2cd09 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -117,7 +117,7 @@ pub struct Card { #[serde(untagged)] pub enum CardPayment { RawCard(Box<Card>), - CardToken(String), + CardToken(Secret<String>), } impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>> @@ -577,7 +577,7 @@ pub struct Shift4ThreeDsResponse { #[derive(Default, Debug, Deserialize, Serialize)] pub struct Token { - pub id: String, + pub id: Secret<String>, pub created: i64, #[serde(rename = "objectType")] pub object_type: String, @@ -629,7 +629,7 @@ pub enum NextAction { #[derive(Debug, Serialize, Deserialize)] pub struct Shift4CardToken { - pub id: String, + pub id: Secret<String>, } impl<F> diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 1e5501575ad..03bd0ac83ee 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -181,7 +181,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SquareSessionResponse { - session_id: String, + session_id: Secret<String>, } impl<F, T> @@ -194,9 +194,9 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { status: storage::enums::AttemptStatus::Pending, - session_token: Some(item.response.session_id.clone()), + session_token: Some(item.response.session_id.clone().expose()), response: Ok(types::PaymentsResponseData::SessionTokenResponse { - session_token: item.response.session_id, + session_token: item.response.session_id.expose(), }), ..item.data })
2024-03-04T07:08:32Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Prophetpay, rapyd, shift4 and square. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a card redirect payment with Prophetpay ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data '{ "amount": 8000, "currency": "USD", "confirm": true, "amount_to_capture": 8000, "business_country": "US", "customer_id": "custhype1232", "return_url": "https://www.google.com", "payment_method": "card_redirect", "payment_method_type": "card_redirect", "payment_method_data": { "card_redirect": { "card_redirect": {} } }, "routing": { "type": "single", "data": "prophetpay" } }' ``` 2.Rapyd Applepay 3.Create a 3DS payment with Shift4 _Note: Currently there is a known bug in this flow. We get an `Unable to parse request - unrecognized field: card[number]` error_ 4.Square card payment there is a known bug - #3974 5. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` 1. Prophetpay Response ``` \"masked_response\":\"{\\\"hostedTokenizeId\\\":\\\"*** alloc::string::String ***\\\"}\ ``` ``` request\":\"{\\\"amount\\\":80.0,\\\"refInfo\\\":\\\"pay_MBu0Wfts32TfURFTNJJn_1\\\",\\\"inquiryReference\\\":\\\"pay_MBu0Wfts32TfURFTNJJn_1\\\",\\\"profile\\\":\\\"*** alloc::string::String ***\\\",\\\"actionType\\\":1,\\\"cardToken\\\":\\\"*** alloc::string::String ***\\\"}\",\"masked_response\":\"{\\\"success\\\":true,\\\"responseText\\\":\\\"Success\\\",\\\"transactionID\\\":\\\"2237854484\\\",\\\"responseCode\\\":\\\"0\\\"} ```
5bb67c7dcc22f9cee51adf501bdd8455b41548db
[ "crates/router/src/connector/prophetpay/transformers.rs", "crates/router/src/connector/rapyd/transformers.rs", "crates/router/src/connector/shift4/transformers.rs", "crates/router/src/connector/square/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3929
Bug: [FEATURE] : [Paypal][Payu][Placetopay][PowerTranz] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index e3ad6f8b426..e8699a1a0ed 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -1,4 +1,5 @@ use base64::Engine; +use common_utils::pii::{Email, IpAddress}; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; @@ -15,7 +16,7 @@ const WALLET_IDENTIFIER: &str = "PBL"; #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsRequest { - customer_ip: std::net::IpAddr, + customer_ip: Secret<String, IpAddress>, merchant_pos_id: Secret<String>, total_amount: i64, currency_code: enums::Currency, @@ -55,7 +56,7 @@ pub struct PayuWallet { pub value: PayuWalletCode, #[serde(rename = "type")] pub wallet_type: String, - pub authorization_code: String, + pub authorization_code: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] @@ -83,8 +84,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { PayuWallet { value: PayuWalletCode::Ap, wallet_type: WALLET_IDENTIFIER.to_string(), - authorization_code: consts::BASE64_ENGINE - .encode(data.tokenization_data.token), + authorization_code: Secret::new( + consts::BASE64_ENGINE.encode(data.tokenization_data.token), + ), } }), }), @@ -93,7 +95,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { PayuWallet { value: PayuWalletCode::Jp, wallet_type: WALLET_IDENTIFIER.to_string(), - authorization_code: data.payment_data, + authorization_code: Secret::new(data.payment_data), } }), }), @@ -111,11 +113,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { }, )?; Ok(Self { - customer_ip: browser_info.ip_address.ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "browser_info.ip_address", - }, - )?, + customer_ip: Secret::new( + browser_info + .ip_address + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "browser_info.ip_address", + })? + .to_string(), + ), merchant_pos_id: auth_type.merchant_pos_id, total_amount: item.request.amount, currency_code: item.request.currency, @@ -401,8 +406,8 @@ pub struct PayuOrderResponseData { ext_order_id: Option<String>, order_create_date: String, notify_url: Option<String>, - customer_ip: std::net::IpAddr, - merchant_pos_id: String, + customer_ip: Secret<String, IpAddress>, + merchant_pos_id: Secret<String>, description: String, validity_time: Option<String>, currency_code: enums::Currency, @@ -417,12 +422,12 @@ pub struct PayuOrderResponseData { #[serde(rename_all = "camelCase")] pub struct PayuOrderResponseBuyerData { ext_customer_id: Option<String>, - email: Option<String>, - phone: Option<String>, - first_name: Option<String>, - last_name: Option<String>, + email: Option<Email>, + phone: Option<Secret<String>>, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, #[serde(rename = "nin")] - national_identification_number: Option<String>, + national_identification_number: Option<Secret<String>>, language: Option<String>, delivery: Option<String>, customer_id: Option<String>, diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index e5dedf6ded0..1c3b46fdb60 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -73,7 +73,7 @@ pub struct PlacetopayAuthType { pub struct PlacetopayAuth { login: Secret<String>, tran_key: Secret<String>, - nonce: String, + nonce: Secret<String>, seed: String, } @@ -179,7 +179,7 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuth { context.update(seed.as_bytes()); context.update(placetopay_auth.tran_key.peek().as_bytes()); let encoded_digest = base64::Engine::encode(&consts::BASE64_ENGINE, context.finish()); - let nonce = base64::Engine::encode(&consts::BASE64_ENGINE, &nonce_bytes); + let nonce = Secret::new(base64::Engine::encode(&consts::BASE64_ENGINE, &nonce_bytes)); Ok(Self { login: placetopay_auth.login, tran_key: encoded_digest.into(), diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs index 53f6a02d5b4..a26886384c0 100644 --- a/crates/router/src/connector/powertranz.rs +++ b/crates/router/src/connector/powertranz.rs @@ -309,7 +309,7 @@ impl .get_redirect_response_payload()? .parse_value("PowerTranz RedirectResponsePayload") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let spi_token = format!(r#""{}""#, redirect_payload.spi_token); + let spi_token = format!(r#""{}""#, redirect_payload.spi_token.expose()); Ok(RequestContent::Json(Box::new(spi_token))) } diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 54849f8bf1d..0af5dde6d00 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -1,8 +1,8 @@ use api_models::payments::Card; -use common_utils::pii::Email; +use common_utils::pii::{Email, IpAddress}; use diesel_models::enums::RefundStatus; use error_stack::IntoReport; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -51,7 +51,7 @@ pub struct BrowserInfo { screen_width: Option<String>, time_zone: Option<String>, user_agent: Option<String>, - i_p: Option<std::net::IpAddr>, + i_p: Option<Secret<String, IpAddress>>, color_depth: Option<String>, } @@ -94,7 +94,7 @@ pub struct PowertranzAddressDetails { #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct RedirectResponsePayload { - pub spi_token: String, + pub spi_token: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest { @@ -173,7 +173,9 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo { screen_width: item.screen_width.map(|width| width.to_string()), time_zone: item.time_zone.map(|zone| zone.to_string()), user_agent: item.user_agent.clone(), - i_p: item.ip_address, + i_p: item + .ip_address + .map(|ip_address| Secret::new(ip_address.to_string())), color_depth: item.color_depth.map(|depth| depth.to_string()), }) } @@ -256,7 +258,7 @@ pub struct PowertranzBaseResponse { original_trxn_identifier: Option<String>, errors: Option<Vec<Error>>, iso_response_code: String, - redirect_data: Option<String>, + redirect_data: Option<Secret<String>>, response_message: String, order_identifier: String, } @@ -322,7 +324,7 @@ impl<F, T> item.response .redirect_data .map(|redirect_data| services::RedirectForm::Html { - html_data: redirect_data, + html_data: redirect_data.expose(), }); let response = error_response.map_or( Ok(types::PaymentsResponseData::TransactionResponse {
2024-03-04T06:54:02Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Payu, Placetopay, PowerTranz and Prophetpay. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a Payu Google pay payment Generate token from : https://jsfiddle.net/1agu74ve/1/ ``` "gateway": "payu" "gatewayMerchantId": "YOUR_GATEWAY_MERCHANT_ID" ``` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{}' \ --data-raw '{ "amount": 1800, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Visa •••• 1111", "info": { "card_network": "VISA", "card_details": "1111" }, "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{{token}}" } } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "Dubai", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "metadata": { "count_tickets": 1, "transaction_number": "5590043" } }' ``` 2. PlaceToPay Card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` 3. PowerTranz ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 20000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000027891380961", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 4. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` 1. Payme Googlepay Response ``` "masked_response\":\"{\\\"status\\\":{\\\"statusCode\\\":\\\"WARNING_CONTINUE_3DS\\\",\\\"severity\\\":\\\"WARNING\\\",\\\"statusDesc\\\":null},\\\"redirectUri\\\":\\\"https://merch-prod.snd.payu.com/front/threeds/?authenticationId=d7b6aa7f-5aa8-467d-adcf-8a8ec9bee28a&refReqId=18c06b1d191d1cf26b93997134d7174d\\\",\\\"iframeAllowed\\\":true,\\\"threeDsProtocolVersion\\\":\\\"3DS2\\\",\\\"orderId\\\":\\\"T9L16ZMRD3240305GUEST000P01\\\",\\\"extOrderId\\\":null} ``` 2. Placetopay Card payment ``` payment request\\\",\\\"amount\\\":{\\\"currency\\\":\\\"COP\\\",\\\"total\\\":320320}},\\\"instrument\\\":{\\\"card\\\":{\\\"number\\\":\\\"411077**********\\\",\\\"expiration\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\"}},\\\"ipAddress\\\":\\\"127.**.**.**\\\",\\\"userAgent\\\":\\\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\\\"}\",\"masked_response\":\"{\\\"status\\\":{\\\"status\\\":\\\"APPROVED\\\"} ``` 3. PowerTranz Card Payment ``` masked_response\":\"{\\\"TransactionType\\\":2,\\\"Approved\\\":false,\\\"TransactionIdentifier\\\":\\\"49da3e97-4f34-4a20-bbfd-204450646191\\\",\\\"OriginalTrxnIdentifier\\\":null,\\\"Errors\\\":null,\\\"IsoResponseCode\\\":\\\"SP4\\\",\\\"RedirectData\\\":\\\"*** alloc::string::String ***\\\",\\\"ResponseMessage\\\":\\\"SPI Preprocessing complete\\\",\\\"OrderIdentifier\\\":\\\"pay_C0D9yBw4FIxAiYSRMGJ2_1\\\"} ``` ## Impacted Area > Payme: Applepay and Googlepay > Placetopay: Card Payment > PowerTranz: Card Payment
13f6d6c10ce421329a7eb8b494fbb3bd31aed91f
1. Create a Payu Google pay payment Generate token from : https://jsfiddle.net/1agu74ve/1/ ``` "gateway": "payu" "gatewayMerchantId": "YOUR_GATEWAY_MERCHANT_ID" ``` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{}' \ --data-raw '{ "amount": 1800, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Visa •••• 1111", "info": { "card_network": "VISA", "card_details": "1111" }, "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{{token}}" } } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "Dubai", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "metadata": { "count_tickets": 1, "transaction_number": "5590043" } }' ``` 2. PlaceToPay Card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` 3. PowerTranz ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 20000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000027891380961", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 4. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` 1. Payme Googlepay Response ``` "masked_response\":\"{\\\"status\\\":{\\\"statusCode\\\":\\\"WARNING_CONTINUE_3DS\\\",\\\"severity\\\":\\\"WARNING\\\",\\\"statusDesc\\\":null},\\\"redirectUri\\\":\\\"https://merch-prod.snd.payu.com/front/threeds/?authenticationId=d7b6aa7f-5aa8-467d-adcf-8a8ec9bee28a&refReqId=18c06b1d191d1cf26b93997134d7174d\\\",\\\"iframeAllowed\\\":true,\\\"threeDsProtocolVersion\\\":\\\"3DS2\\\",\\\"orderId\\\":\\\"T9L16ZMRD3240305GUEST000P01\\\",\\\"extOrderId\\\":null} ``` 2. Placetopay Card payment ``` payment request\\\",\\\"amount\\\":{\\\"currency\\\":\\\"COP\\\",\\\"total\\\":320320}},\\\"instrument\\\":{\\\"card\\\":{\\\"number\\\":\\\"411077**********\\\",\\\"expiration\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\"}},\\\"ipAddress\\\":\\\"127.**.**.**\\\",\\\"userAgent\\\":\\\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\\\"}\",\"masked_response\":\"{\\\"status\\\":{\\\"status\\\":\\\"APPROVED\\\"} ``` 3. PowerTranz Card Payment ``` masked_response\":\"{\\\"TransactionType\\\":2,\\\"Approved\\\":false,\\\"TransactionIdentifier\\\":\\\"49da3e97-4f34-4a20-bbfd-204450646191\\\",\\\"OriginalTrxnIdentifier\\\":null,\\\"Errors\\\":null,\\\"IsoResponseCode\\\":\\\"SP4\\\",\\\"RedirectData\\\":\\\"*** alloc::string::String ***\\\",\\\"ResponseMessage\\\":\\\"SPI Preprocessing complete\\\",\\\"OrderIdentifier\\\":\\\"pay_C0D9yBw4FIxAiYSRMGJ2_1\\\"} ```
[ "crates/router/src/connector/payu/transformers.rs", "crates/router/src/connector/placetopay/transformers.rs", "crates/router/src/connector/powertranz.rs", "crates/router/src/connector/powertranz/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3927
Bug: [FEATURE] : [Payme][Payeezy] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 90b4b0b0bba..6d5d6db9dcf 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -1,7 +1,7 @@ use cards::CardNumber; use common_utils::ext_traits::Encode; use error_stack::ResultExt; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -108,7 +108,7 @@ pub struct StoredCredentials { pub sequence: Sequence, pub initiator: Initiator, pub is_scheduled: bool, - pub cardbrand_original_transaction_id: Option<String>, + pub cardbrand_original_transaction_id: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] @@ -203,7 +203,7 @@ fn get_transaction_type_and_stored_creds( }, is_scheduled: true, // In case of first mandate payment connector_mandate_id would be None, otherwise holds some value - cardbrand_original_transaction_id: connector_mandate_id, + cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new), }), ) } else { @@ -329,7 +329,7 @@ pub struct PayeezyPaymentsResponse { #[derive(Debug, Deserialize, Serialize)] pub struct PaymentsStoredCredentials { - cardbrand_original_transaction_id: String, + cardbrand_original_transaction_id: Secret<String>, } #[derive(Debug, Serialize)] @@ -416,7 +416,7 @@ impl<F, T> .stored_credentials .map(|credentials| credentials.cardbrand_original_transaction_id) .map(|id| types::MandateReference { - connector_mandate_id: Some(id), + connector_mandate_id: Some(id.expose()), payment_method_id: None, }); let status = enums::AttemptStatus::foreign_from(( diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index ee0d52bae50..fd638f5b606 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -84,7 +84,7 @@ pub struct Pay3dsRequest { buyer_email: pii::Email, buyer_key: String, payme_sale_id: String, - meta_data_jwt: String, + meta_data_jwt: Secret<String>, } #[derive(Debug, Serialize)] @@ -122,7 +122,7 @@ pub struct CaptureBuyerRequest { #[derive(Debug, Deserialize, Serialize)] pub struct CaptureBuyerResponse { - buyer_key: String, + buyer_key: Secret<String>, } #[derive(Debug, Serialize)] @@ -719,7 +719,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { buyer_key, buyer_name, payme_sale_id, - meta_data_jwt: jwt_data.meta_data, + meta_data_jwt: Secret::new(jwt_data.meta_data), }) } Some(api::PaymentMethodData::CardRedirect(_)) @@ -902,10 +902,10 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { payment_method_token: Some(types::PaymentMethodToken::Token( - item.response.buyer_key.clone(), + item.response.buyer_key.clone().expose(), )), response: Ok(types::PaymentsResponseData::TokenizationResponse { - token: item.response.buyer_key, + token: item.response.buyer_key.expose(), }), ..item.data })
2024-03-04T06:33:46Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Payme and Payeezy. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a 3ds payment with payme ``` curl --location 'https://cee4-219-65-110-2.ngrok-free.app/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "gnana" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "gnana" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ] }' ``` 1.b. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` "masked_response\":\"{\\\"buyer_key\\\":\\\"*** alloc::string::String ***\\\"} ``` _Note: Don't have credentials to test payeezy_
fee0663d665576cc80e0a8512fd8b36c91850332
[ "crates/router/src/connector/payeezy/transformers.rs", "crates/router/src/connector/payme/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3925
Bug: [FEATURE] : [Nuvei] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 8d3be455d49..0e9a9634402 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -9,6 +9,7 @@ use ::common_utils::{ request::RequestContent, }; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use transformers as nuvei; use super::utils::{self, RouterData}; @@ -1010,7 +1011,7 @@ impl services::ConnectorRedirectResponse for Nuvei { let redirect_response: nuvei::NuveiRedirectionResponse = payload.parse_value("NuveiRedirectionResponse").switch()?; let acs_response: nuvei::NuveiACSResponse = - utils::base64_decode(redirect_response.cres)? + utils::base64_decode(redirect_response.cres.expose())? .as_slice() .parse_struct("NuveiACSResponse") .switch()?; diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 1312eadadf7..6c99536109b 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -3,12 +3,12 @@ use common_utils::{ crypto::{self, GenerateDigest}, date_time, ext_traits::Encode, - fp_utils, pii, - pii::Email, + fp_utils, + pii::{Email, IpAddress}, }; use data_models::mandates::MandateDataType; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -26,7 +26,7 @@ use crate::{ #[derive(Debug, Serialize, Default, Deserialize)] pub struct NuveiMeta { - pub session_token: String, + pub session_token: Secret<String>, } #[derive(Debug, Serialize, Default, Deserialize)] @@ -41,19 +41,19 @@ pub struct NuveiSessionRequest { pub merchant_site_id: Secret<String>, pub client_request_id: String, pub time_stamp: date_time::DateTime<date_time::YYYYMMDDHHmmss>, - pub checksum: String, + pub checksum: Secret<String>, } #[derive(Debug, Serialize, Default, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiSessionResponse { - pub session_token: String, + pub session_token: Secret<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 merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, pub version: String, pub client_request_id: String, } @@ -63,7 +63,7 @@ pub struct NuveiSessionResponse { #[serde(rename_all = "camelCase")] pub struct NuveiPaymentsRequest { pub time_stamp: String, - pub session_token: String, + pub session_token: Secret<String>, pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: Secret<String>, @@ -76,7 +76,7 @@ pub struct NuveiPaymentsRequest { pub is_rebilling: Option<String>, pub payment_option: PaymentOption, pub device_details: Option<DeviceDetails>, - pub checksum: String, + pub checksum: Secret<String>, pub billing_address: Option<BillingAddress>, pub related_transaction_id: Option<String>, pub url_details: Option<UrlDetails>, @@ -92,14 +92,14 @@ pub struct UrlDetails { #[derive(Debug, Serialize, Default)] pub struct NuveiInitPaymentRequest { - pub session_token: String, - pub merchant_id: String, - pub merchant_site_id: String, + pub session_token: Secret<String>, + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, pub client_request_id: String, pub amount: String, pub currency: String, pub payment_option: PaymentOption, - pub checksum: String, + pub checksum: Secret<String>, } /// Handles payment request for capture, void and refund flows @@ -113,13 +113,13 @@ pub struct NuveiPaymentFlowRequest { pub amount: String, pub currency: diesel_models::enums::Currency, pub related_transaction_id: Option<String>, - pub checksum: String, + pub checksum: Secret<String>, } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentSyncRequest { - pub session_token: String, + pub session_token: Secret<String>, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -217,12 +217,12 @@ pub struct Card { #[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 cc_card_number: Option<Secret<String>>, + pub bin: Option<Secret<String>>, + pub last4_digits: Option<Secret<String>>, + pub cc_exp_month: Option<Secret<String>>, + pub cc_exp_year: Option<Secret<String>>, + pub acquirer_id: Option<Secret<String>>, pub cvv2_reply: Option<String>, pub avs_code: Option<String>, pub card_type: Option<String>, @@ -260,7 +260,7 @@ pub struct ThreeD { #[serde(rename = "merchantURL")] pub merchant_url: Option<String>, pub acs_url: Option<String>, - pub c_req: Option<String>, + pub c_req: Option<Secret<String>>, pub platform_type: Option<PlatformType>, pub v2supported: Option<String>, pub v2_additional_params: Option<V2AdditionalParams>, @@ -291,7 +291,7 @@ pub enum PlatformType { #[serde(rename_all = "camelCase")] pub struct BrowserDetails { pub accept_header: String, - pub ip: Secret<String, pii::IpAddress>, + pub ip: Secret<String, IpAddress>, pub java_enabled: String, pub java_script_enabled: String, pub language: String, @@ -315,7 +315,7 @@ pub struct V2AdditionalParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceDetails { - pub ip_address: Secret<String, pii::IpAddress>, + pub ip_address: Secret<String, IpAddress>, } impl From<enums::CaptureMethod> for TransactionType { @@ -329,15 +329,15 @@ impl From<enums::CaptureMethod> for TransactionType { #[derive(Debug, Serialize, Deserialize)] pub struct NuveiRedirectionResponse { - pub cres: String, + pub cres: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiACSResponse { #[serde(rename = "threeDSServerTransID")] - pub three_ds_server_trans_id: String, + pub three_ds_server_trans_id: Secret<String>, #[serde(rename = "acsTransID")] - pub acs_trans_id: String, + pub acs_trans_id: Secret<String>, pub message_type: String, pub message_version: String, pub trans_status: Option<LiabilityShift>, @@ -394,13 +394,13 @@ impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRe merchant_site_id: merchant_site_id.clone(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), - checksum: encode_payload(&[ + checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, &time_stamp.to_string(), merchant_secret.peek(), - ])?, + ])?), }) } } @@ -415,9 +415,9 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Pending, - session_token: Some(item.response.session_token.clone()), + session_token: Some(item.response.session_token.clone().expose()), response: Ok(types::PaymentsResponseData::SessionTokenResponse { - session_token: item.response.session_token, + session_token: item.response.session_token.expose(), }), ..item.data }) @@ -866,7 +866,7 @@ impl<F> currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.connector_request_reference_id.clone(), - session_token: data.1, + session_token: Secret::new(data.1), capture_method: item.request.capture_method, ..Default::default() })?; @@ -1015,10 +1015,12 @@ impl From<NuveiCardDetails> for PaymentOption { } } -impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPaymentsRequest { +impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> + for NuveiPaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - data: (&types::PaymentsCompleteAuthorizeRouterData, String), + data: (&types::PaymentsCompleteAuthorizeRouterData, Secret<String>), ) -> Result<Self, Self::Error> { let item = data.0; let request_data = match item.request.payment_method_data.clone() { @@ -1067,7 +1069,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(request: NuveiPaymentRequestData) -> Result<Self, Self::Error> { let session_token = request.session_token; - fp_utils::when(session_token.is_empty(), || { + fp_utils::when(session_token.clone().expose().is_empty(), || { Err(errors::ConnectorError::FailedToObtainAuthType) })?; let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&request.connector_auth_type)?; @@ -1089,7 +1091,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { .capture_method .map(TransactionType::from) .unwrap_or_default(), - checksum: encode_payload(&[ + checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, @@ -1097,7 +1099,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { &request.currency.to_string(), &time_stamp, merchant_secret.peek(), - ])?, + ])?), amount: request.amount, currency: request.currency, ..Default::default() @@ -1122,7 +1124,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { merchant_site_id: merchant_site_id.to_owned(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), - checksum: encode_payload(&[ + checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, @@ -1131,7 +1133,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { &request.related_transaction_id.clone().unwrap_or_default(), &time_stamp, merchant_secret.peek(), - ])?, + ])?), amount: request.amount, currency: request.currency, related_transaction_id: request.related_transaction_id, @@ -1146,7 +1148,7 @@ pub struct NuveiPaymentRequestData { pub related_transaction_id: Option<String>, pub client_request_id: String, pub connector_auth_type: types::ConnectorAuthType, - pub session_token: String, + pub session_token: Secret<String>, pub capture_method: Option<diesel_models::enums::CaptureMethod>, } @@ -1273,7 +1275,7 @@ impl From<NuveiTransactionStatus> for enums::AttemptStatus { #[serde(rename_all = "camelCase")] pub struct NuveiPaymentsResponse { pub order_id: Option<String>, - pub user_token_id: Option<String>, + pub user_token_id: Option<Secret<String>>, pub payment_option: Option<PaymentOption>, pub transaction_status: Option<NuveiTransactionStatus>, pub gw_error_code: Option<i64>, @@ -1287,15 +1289,16 @@ pub struct NuveiPaymentsResponse { 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 external_scheme_transaction_id: Option<Secret<String>>, + pub session_token: Option<Secret<String>>, + //The ID of the transaction in the merchant’s system. 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 merchant_id: Option<Secret<String>>, + pub merchant_site_id: Option<Secret<String>>, pub version: Option<String>, pub client_request_id: Option<String>, } @@ -1417,7 +1420,10 @@ where .map(|(base_url, creq)| services::RedirectForm::Form { endpoint: base_url, method: services::Method::Post, - form_fields: std::collections::HashMap::from([("creq".to_string(), creq)]), + form_fields: std::collections::HashMap::from([( + "creq".to_string(), + creq.expose(), + )]), }), };
2024-03-04T06:23:42Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Nuvie. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 20000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000027891380961", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 2. Check if `subscription_data.identifier` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` masked_response\":\"{\\\"orderId\\\":\\\"425682678\\\",\\\"userTokenId\\\":null,\\\"paymentOption\\\":{\\\"card\\\":{\\\"threeD\\\":{\\\"version\\\":\\\"\\\",\\\"cReq\\\":\\\"*** alloc::string::String ***\\\"},\\\"ccCardNumber\\\":\\\"*** alloc::string::String ***\\\",\\\"bin\\\":\\\"*** alloc::string::String ***\\\",\\\"last4Digits\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpYear\\\":\\\"*** alloc::string::String ***\\\",\\\"acquirerId\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv2Reply\\\":\\\"\\\",\\\"avsCode\\\":\\\"\\\",\\\"cardType\\\":\\\"Credit\\\",\\\"cardBrand\\\":\\\"VISA\\\",\\\"issuerBankName\\\":\\\"River Valley Credit Union\\\",\\\"issuerCountry\\\":\\\"GB\\\",\\\"isPrepaid\\\":\\\"false\\\"},\\\"userPaymentOptionId\\\":\\\"\\\"},\\\"transactionStatus\\\":\\\"ERROR\\\",\\\"gwErrorCode\\\":-1,\\\"gwErrorReason\\\":\\\"UNEXPECTED SYSTEM ERROR - PLEASE RETRY LATER\\\",\\\"gwExtendedErrorCode\\\":-1,\\\"issuerDeclineCode\\\":\\\"\\\",\\\"issuerDeclineReason\\\":\\\"\\\",\\\"transactionType\\\":\\\"Auth3D\\\",\\\"transactionId\\\":\\\"711000000033006423\\\",\\\"externalTransactionId\\\":\\\"\\\",\\\"authCode\\\":\\\"\\\",\\\"customData\\\":\\\"\\\",\\\"fraudDetails\\\":null,\\\"externalSchemeTransactionId\\\":\\\"*** alloc::string::String ***\\\",\\\"sessionToken\\\":\\\"*** alloc::string::String ***\\\",\\\"clientUniqueId\\\":\\\"\\\",\\\"internalRequestId\\\":944545618,\\\"status\\\":\\\"SUCCESS\\\",\\\"errCode\\\":0,\\\"reason\\\":\\\"\\\",\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantSiteId\\\":\\\"*** alloc::string::String ***\\\",\\\"version\\\":\\\"1.0\\\",\\\"clientRequestId\\\":\\\"pay_oVLDU95Hwm0D4tjm6CH6_1\\\"} ```
0cb95a4911054e089e6ed3c528645ee1b881ebc6
1. Create a card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 20000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000027891380961", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 2. Check if `subscription_data.identifier` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` masked_response\":\"{\\\"orderId\\\":\\\"425682678\\\",\\\"userTokenId\\\":null,\\\"paymentOption\\\":{\\\"card\\\":{\\\"threeD\\\":{\\\"version\\\":\\\"\\\",\\\"cReq\\\":\\\"*** alloc::string::String ***\\\"},\\\"ccCardNumber\\\":\\\"*** alloc::string::String ***\\\",\\\"bin\\\":\\\"*** alloc::string::String ***\\\",\\\"last4Digits\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpYear\\\":\\\"*** alloc::string::String ***\\\",\\\"acquirerId\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv2Reply\\\":\\\"\\\",\\\"avsCode\\\":\\\"\\\",\\\"cardType\\\":\\\"Credit\\\",\\\"cardBrand\\\":\\\"VISA\\\",\\\"issuerBankName\\\":\\\"River Valley Credit Union\\\",\\\"issuerCountry\\\":\\\"GB\\\",\\\"isPrepaid\\\":\\\"false\\\"},\\\"userPaymentOptionId\\\":\\\"\\\"},\\\"transactionStatus\\\":\\\"ERROR\\\",\\\"gwErrorCode\\\":-1,\\\"gwErrorReason\\\":\\\"UNEXPECTED SYSTEM ERROR - PLEASE RETRY LATER\\\",\\\"gwExtendedErrorCode\\\":-1,\\\"issuerDeclineCode\\\":\\\"\\\",\\\"issuerDeclineReason\\\":\\\"\\\",\\\"transactionType\\\":\\\"Auth3D\\\",\\\"transactionId\\\":\\\"711000000033006423\\\",\\\"externalTransactionId\\\":\\\"\\\",\\\"authCode\\\":\\\"\\\",\\\"customData\\\":\\\"\\\",\\\"fraudDetails\\\":null,\\\"externalSchemeTransactionId\\\":\\\"*** alloc::string::String ***\\\",\\\"sessionToken\\\":\\\"*** alloc::string::String ***\\\",\\\"clientUniqueId\\\":\\\"\\\",\\\"internalRequestId\\\":944545618,\\\"status\\\":\\\"SUCCESS\\\",\\\"errCode\\\":0,\\\"reason\\\":\\\"\\\",\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantSiteId\\\":\\\"*** alloc::string::String ***\\\",\\\"version\\\":\\\"1.0\\\",\\\"clientRequestId\\\":\\\"pay_oVLDU95Hwm0D4tjm6CH6_1\\\"} ```
[ "crates/router/src/connector/nuvei.rs", "crates/router/src/connector/nuvei/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3748
Bug: [FEATURE]: add `offset` field to mandates list ### Feature Description The [mandates list](https://github.com/juspay/hyperswitch/blob/54c0b218d9f20c6388dde0f30ea525011cdad573/crates/router/src/routes/mandates.rs#L114) endpoint currently has no field to specify `offset`, which would skip certain number of entries from the start. This is necessary in order to provide pagination support. ### Possible Implementation accept a field called `offset` which specifies the number of items to skip from the start. This would be similar to the `payments_list` pagination. Refer [here](https://github.com/juspay/hyperswitch/blob/54c0b218d9f20c6388dde0f30ea525011cdad573/crates/router/src/routes/payments.rs#L868) ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 7c20a902d28..bd5c5b5a1a0 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -87,6 +87,8 @@ pub struct MandateCardDetails { pub struct MandateListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, + /// offset on the number of objects to return + pub offset: Option<i64>, /// status of the mandate pub mandate_status: Option<api_enums::MandateStatus>, /// connector linked to mandate diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index eb2859e57e1..936344f5af5 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -262,14 +262,22 @@ impl MandateInterface for MockDb { checker }); + #[allow(clippy::as_conversions)] + let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 { + 0 + } else { + mandate_constraints.offset.unwrap_or(0) + }) as usize; + let mandates: Vec<storage::Mandate> = if let Some(limit) = mandate_constraints.limit { #[allow(clippy::as_conversions)] mandates_iter + .skip(offset) .take((if limit < 0 { 0 } else { limit }) as usize) .cloned() .collect() } else { - mandates_iter.cloned().collect() + mandates_iter.skip(offset).cloned().collect() }; Ok(mandates) } diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 1203b766cbb..3e47d78da8a 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -101,6 +101,7 @@ pub async fn revoke_mandate( ("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"), ("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"), ("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"), + ("offset" = Option<i64>, Query, description = "The number of Mandate Objects to skip when retrieving the list Mandates."), ), responses( (status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>), diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs index 32c0798e95c..05a5733053f 100644 --- a/crates/router/src/types/storage/mandate.rs +++ b/crates/router/src/types/storage/mandate.rs @@ -54,6 +54,9 @@ impl MandateDbExt for Mandate { if let Some(limit) = mandate_list_constraints.limit { filter = filter.limit(limit); } + if let Some(offset) = mandate_list_constraints.offset { + filter = filter.offset(offset); + } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
2024-03-03T10:30:15Z
## Description <!-- Describe your changes in detail --> Add offset to mandate list endpoint. Closes #3748 ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create 10 mandates. - Use the below curl to list the first 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ``` - Use the below curl to list next 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5&offset=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ```
a2f179350a7e5819db1b6088b75ff3a7b1ad9bad
- Create 10 mandates. - Use the below curl to list the first 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ``` - Use the below curl to list next 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5&offset=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ```
[ "crates/api_models/src/mandates.rs", "crates/router/src/db/mandate.rs", "crates/router/src/routes/mandates.rs", "crates/router/src/types/storage/mandate.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3920
Bug: [BUG] hotfix: insert locker_id as null in case of payment method not getting stored in locker If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store locker_id column as NULL in payment_methods table
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8c00938cadc..bea888dcce6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -351,7 +351,13 @@ pub async fn add_payment_method( None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); - let locker_id = Some(resp.payment_method_id); + let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card + || resp.payment_method == api_enums::PaymentMethod::BankTransfer + { + Some(resp.payment_method_id) + } else { + None + }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); insert_payment_method( db, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 21fd4cf85e8..1f793e2e185 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,4 +1,5 @@ use api_models::payment_methods::PaymentMethodsData; +use common_enums::PaymentMethod; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -342,7 +343,11 @@ where None => { let pm_metadata = create_payment_method_metadata(None, connector_token)?; - locker_id = Some(resp.payment_method_id); + locker_id = if resp.payment_method == PaymentMethod::Card { + Some(resp.payment_method_id) + } else { + None + }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( db,
2024-03-01T15:28:11Z
## Description <!-- Describe your changes in detail --> Main PR - https://github.com/juspay/hyperswitch/pull/3919 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
0bca3d757c58d425813c051e263febd8d385a587
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/tokenization.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3918
Bug: [BUG] insert `locker_id` as null in case of payment method not getting stored in locker If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store `locker_id` column as `NULL` in payment_methods table
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4f691859215..ce7f48405e2 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -351,7 +351,13 @@ pub async fn add_payment_method( None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); - let locker_id = Some(resp.payment_method_id); + let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card + || resp.payment_method == api_enums::PaymentMethod::BankTransfer + { + Some(resp.payment_method_id) + } else { + None + }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); insert_payment_method( db, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 21fd4cf85e8..1f793e2e185 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,4 +1,5 @@ use api_models::payment_methods::PaymentMethodsData; +use common_enums::PaymentMethod; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -342,7 +343,11 @@ where None => { let pm_metadata = create_payment_method_metadata(None, connector_token)?; - locker_id = Some(resp.payment_method_id); + locker_id = if resp.payment_method == PaymentMethod::Card { + Some(resp.payment_method_id) + } else { + None + }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( db,
2024-03-01T14:58:08Z
## Description <!-- Describe your changes in detail --> If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store `locker_id` column as `NULL` in payment_methods table. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create an MCA ``` curl --location 'http://localhost:8080/account/merchant_1709304245/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "business_label": "default", "business_country": "US", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "affirm" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "afterpay_clearpay" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "klarna" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "invoke_sdk_client", "payment_method_type": "klarna" } ] }, { "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 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "przelewy24", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "blik", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_transfer", "payment_method_types": [ { "payment_method_type": "ach", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sepa", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "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 } ] } ] }' ``` 2. Create a bank debit payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_U44vOQtigGfoj1w2A0F0B9kLlXdZqTR8RRg3JwfPUJhLywIG4PdR1HZD0inVkS2f' \ --data-raw '{ "amount": 1800, "currency": "USD", "confirm": true, "business_label": "default", "capture_method": "automatic", "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "email": "guest1@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "return_url": "https://google.com", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session", "business_country": "US", "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { "bank_debit": { "ach_bank_debit": { "billing_details": { "name": "John Doe", "email": "johndoe@example.com" }, "account_number": "000123456789", "routing_number": "110000000" } } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1800, "account_name": "transaction_processing" } } }' ``` In this case `locker_id` has to be NULL in payment_methods table ![image](https://github.com/juspay/hyperswitch/assets/70657455/3048849c-1230-46b8-b636-d7ea0878ee56)
816266819928477738f70b782eab0e26b600b171
1. Create an MCA ``` curl --location 'http://localhost:8080/account/merchant_1709304245/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "business_label": "default", "business_country": "US", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "affirm" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "afterpay_clearpay" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "klarna" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "invoke_sdk_client", "payment_method_type": "klarna" } ] }, { "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 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "przelewy24", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "blik", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_transfer", "payment_method_types": [ { "payment_method_type": "ach", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sepa", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "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 } ] } ] }' ``` 2. Create a bank debit payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_U44vOQtigGfoj1w2A0F0B9kLlXdZqTR8RRg3JwfPUJhLywIG4PdR1HZD0inVkS2f' \ --data-raw '{ "amount": 1800, "currency": "USD", "confirm": true, "business_label": "default", "capture_method": "automatic", "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "email": "guest1@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "return_url": "https://google.com", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session", "business_country": "US", "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { "bank_debit": { "ach_bank_debit": { "billing_details": { "name": "John Doe", "email": "johndoe@example.com" }, "account_number": "000123456789", "routing_number": "110000000" } } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1800, "account_name": "transaction_processing" } } }' ``` In this case `locker_id` has to be NULL in payment_methods table ![image](https://github.com/juspay/hyperswitch/assets/70657455/3048849c-1230-46b8-b636-d7ea0878ee56)
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/tokenization.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3911
Bug: [FEATURE] : Add `WASM` support for `endpoint_prefix` in dashboard ### Feature Description Add WASM configs for dashboard to take `endpoint_prefix` as input for Adyen Connector Create. ### Possible Implementation Add WASM configs for dashboard to take `endpoint_prefix` as input for Adyen Connector Create. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index c3cbaab4ab3..2af5b88b337 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -81,6 +81,7 @@ pub struct ApiModelMetaData { pub google_pay: Option<GoogleApiModelData>, pub apple_pay: Option<ApplePayData>, pub apple_pay_combined: Option<ApplePayData>, + pub endpoint_prefix: Option<String>, } #[serde_with::skip_serializing_none] @@ -173,4 +174,5 @@ pub struct DashboardMetaData { pub google_pay: Option<GooglePayData>, pub apple_pay: Option<ApplePayData>, pub apple_pay_combined: Option<ApplePayData>, + pub endpoint_prefix: Option<String>, } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index f0997d53107..357ee0cb73f 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -74,6 +74,7 @@ pub struct ConfigMetadata { pub google_pay: Option<GooglePayData>, pub apple_pay: Option<ApplePayTomlConfig>, pub merchant_id: Option<String>, + pub endpoint_prefix: Option<String>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs index 80332612c13..5942a9e01ae 100644 --- a/crates/connector_configs/src/response_modifier.rs +++ b/crates/connector_configs/src/response_modifier.rs @@ -293,6 +293,10 @@ impl ConnectorApiIntegrationPayload { Some(meta_data) => meta_data.terminal_id, _ => None, }; + let endpoint_prefix = match response.metadata.clone() { + Some(meta_data) => meta_data.endpoint_prefix, + _ => None, + }; let apple_pay = match response.metadata.clone() { Some(meta_data) => meta_data.apple_pay, _ => None, @@ -315,6 +319,7 @@ impl ConnectorApiIntegrationPayload { account_name, terminal_id, merchant_id, + endpoint_prefix, }; DashboardRequestPayload { diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index be68a0c5f94..735178cd676 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -186,6 +186,7 @@ impl DashboardRequestPayload { merchant_account_id: None, merchant_id: None, merchant_config_currency: None, + endpoint_prefix: None, }; let meta_data = match request.metadata { Some(data) => data, @@ -196,6 +197,7 @@ impl DashboardRequestPayload { let merchant_account_id = meta_data.merchant_account_id.clone(); let merchant_id = meta_data.merchant_id.clone(); let terminal_id = meta_data.terminal_id.clone(); + let endpoint_prefix = meta_data.endpoint_prefix.clone(); let apple_pay = meta_data.apple_pay; let apple_pay_combined = meta_data.apple_pay_combined; let merchant_config_currency = meta_data.merchant_config_currency; @@ -208,6 +210,7 @@ impl DashboardRequestPayload { merchant_id, merchant_config_currency, apple_pay_combined, + endpoint_prefix, }) } diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index a616f302cfc..0310944de7e 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -372,6 +372,9 @@ pub enum BankNames { TsbBank, TescoBank, UlsterBank, + Yoursafe, + N26, + NationaleNederlanden, } #[derive( diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 261495e2bfa..93301364e62 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -280,10 +280,12 @@ fn build_env_specific_endpoint( } else { let adyen_connector_metadata_object = transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?; - Ok(base_url.replace( - "{{merchant_endpoint_prefix}}", - &adyen_connector_metadata_object.endpoint_prefix, - )) + let endpoint_prefix = adyen_connector_metadata_object.endpoint_prefix.ok_or( + errors::ConnectorError::InvalidConnectorConfig { + config: "metadata.endpoint_prefix", + }, + )?; + Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) } } @@ -1556,17 +1558,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Adyen { - fn build_request( - &self, - _req: &types::RefundsRouterData<api::RSync>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::FlowNotSupported { - flow: "Rsync".to_owned(), - connector: "Adyen".to_owned(), - } - .into()) - } } fn get_webhook_object_from_body( diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 7f20041e1fc..9fbf7d99812 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -63,7 +63,7 @@ impl<T> } #[derive(Debug, Default, Serialize, Deserialize)] pub struct AdyenConnectorMetadataObject { - pub endpoint_prefix: String, + pub endpoint_prefix: Option<String>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject { @@ -106,7 +106,8 @@ pub enum AuthType { #[serde(rename_all = "camelCase")] pub struct AdditionalData { authorisation_type: Option<AuthType>, - manual_capture: Option<bool>, + manual_capture: Option<String>, + execute_three_d: Option<String>, pub recurring_processing_model: Option<AdyenRecurringModel>, /// Enable recurring details in dashboard to receive this ID, https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#test-and-go-live #[serde(rename = "recurring.recurringDetailReference")] @@ -1641,19 +1642,28 @@ fn get_browser_info( } fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> { - match item.request.capture_method { + let (authorisation_type, manual_capture) = match item.request.capture_method { Some(diesel_models::enums::CaptureMethod::Manual) - | Some(diesel_models::enums::CaptureMethod::ManualMultiple) => Some(AdditionalData { - authorisation_type: Some(AuthType::PreAuth), - manual_capture: Some(true), - network_tx_reference: None, - recurring_detail_reference: None, - recurring_shopper_reference: None, - recurring_processing_model: Some(AdyenRecurringModel::UnscheduledCardOnFile), - ..AdditionalData::default() - }), - _ => None, - } + | Some(diesel_models::enums::CaptureMethod::ManualMultiple) => { + (Some(AuthType::PreAuth), Some("true".to_string())) + } + _ => (None, None), + }; + let execute_three_d = if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) { + Some("true".to_string()) + } else { + None + }; + Some(AdditionalData { + authorisation_type, + manual_capture, + execute_three_d, + network_tx_reference: None, + recurring_detail_reference: None, + recurring_shopper_reference: None, + recurring_processing_model: None, + ..AdditionalData::default() + }) } fn get_channel_type(pm_type: &Option<storage_enums::PaymentMethodType>) -> Option<Channel> { @@ -3809,7 +3819,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AdyenRefundResponse>> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: item.response.reference, + connector_refund_id: item.response.psp_reference, // From the docs, the only value returned is "received", outcome of refund is available // through refund notification webhook // For more info: https://docs.adyen.com/online-payments/refund diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js index dcf3f191643..cfbd9695bd1 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js @@ -22,7 +22,7 @@ pm.test("[POST]::/payments/:id/cancel - Response has JSON Body", function () { let jsonData = {}; try { jsonData = pm.response.json(); -} catch (e) {} +} catch (e) { } // pm.collectionVariables - Set payment_id as variable for jsonData.payment_id if (jsonData?.payment_id) { @@ -53,9 +53,9 @@ if (jsonData?.client_secret) { // Response body should have value "cancelled" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'", + "[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("cancelled"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js index 5e52e13a59e..ec02aad8626 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js @@ -19,7 +19,7 @@ pm.test("[GET]::/payments/:id - Response has JSON Body", function () { let jsonData = {}; try { jsonData = pm.response.json(); -} catch (e) {} +} catch (e) { } // pm.collectionVariables - Set payment_id as variable for jsonData.payment_id if (jsonData?.payment_id) { @@ -63,9 +63,9 @@ if (jsonData?.client_secret) { // Response body should have value "cancelled" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'", + "[POST]::/payments/:id - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("cancelled"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json index b5002aeca8e..401201dff64 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -46,7 +46,7 @@ "key1": "{{connector_key1}}", "api_secret": "{{connector_api_secret}}" }, - "test_mode": false, + "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", @@ -56,12 +56,17 @@ "payment_method_types": [ { "payment_method_type": "credit", - "card_networks": ["AmericanExpress", - "Discover", - "Interac", - "JCB", - "Mastercard", - "Visa", "DinersClub","UnionPay","RuPay"], + "card_networks": [ + "AmericanExpress", + "Discover", + "Interac", + "JCB", + "Mastercard", + "Visa", + "DinersClub", + "UnionPay", + "RuPay" + ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, @@ -69,12 +74,17 @@ }, { "payment_method_type": "debit", - "card_networks": ["AmericanExpress", - "Discover", - "Interac", - "JCB", - "Mastercard", - "Visa", "DinersClub","UnionPay","RuPay"], + "card_networks": [ + "AmericanExpress", + "Discover", + "Interac", + "JCB", + "Mastercard", + "Visa", + "DinersClub", + "UnionPay", + "RuPay" + ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, @@ -203,15 +213,15 @@ { "payment_method": "gift_card", "payment_method_types": [ - { - "payment_method_type": "givex", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - } + { + "payment_method_type": "givex", + "minimum_amount": 1, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": true + } ] - }, + }, { "payment_method": "bank_redirect", "payment_method_types": [ @@ -303,7 +313,10 @@ { "type": "CARD", "parameters": { - "allowed_auth_methods": ["PAN_ONLY", "CRYPTOGRAM_3DS"], + "allowed_auth_methods": [ + "PAN_ONLY", + "CRYPTOGRAM_3DS" + ], "allowed_card_networks": [ "AMEX", "DISCOVER", @@ -327,8 +340,14 @@ }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": ["{{baseUrl}}"], - "path": ["account", ":account_id", "connectors"], + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], "variable": [ { "key": "account_id", @@ -338,4 +357,4 @@ ] }, "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." -} +} \ No newline at end of file
2024-03-01T10:37:16Z
## Description <!-- Describe your changes in detail --> - Update Connector Account configs for WASM build - Update Postman Collection test case for Cancelled payments - Make `endpoint_prefix` as Optional in MCA-create - Change `connector_refund_id` to `psp_reference` - Add support to enforce 3DS ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3911 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a manual capture payment and Cancel it, it should go into processing ``` curl --location 'http://localhost:8080/payments/pay_7RzGoWYbCpeSHynBpytc/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LyWBxSXvkIRgcdWNLamgVQul9tMWq2axdKYlmJSwSFbv0nfDsppaJ6UwSbny0PBm' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` RESPONSE: ``` { "payment_id": "pay_AF6YTcabCeegWRQUWjdZ", "merchant_id": "postman_merchant_GHAction_b6d214c4-4173-4a86-b4e1-52478efba2ca", "status": "processing", "amount": 2134, "net_amount": 2134, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_AF6YTcabCeegWRQUWjdZ_secret_fkz68YL0UTuAJ64Tlji8", "created": "2024-03-01T08:35:04.606Z", "currency": "USD", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "H2GSJ9JB3RJWHST5", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_AF6YTcabCeegWRQUWjdZ_1", "payment_link": null, "profile_id": "pro_KNzwSZXU8MXNySCtfhtI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_kwbRKJxDNAJaEtZkdVFF", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T08:50:04.606Z", "fingerprint": null } ``` - For Refunds Check the `connector_refund_id` and match with Connector psp_reference - Test 3DS payments with normal card and `auth_type` as `three_ds`, 3DS should be triggered ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5dUdESXJ81peNfBZoKwB47YehzdbXBzraGgh69wH0ZtFad9hHHT3isDg7ymJiHZc' \ --data-raw '{ "amount": 2121, "currency": "CZK", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 2121, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "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" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` RESPONSE: ``` { "payment_id": "pay_BgVVHyaRkDKAoQJVDNPR", "merchant_id": "postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085", "status": "requires_customer_action", "amount": 2121, "net_amount": 2121, "amount_capturable": 2121, "amount_received": null, "connector": "adyen", "client_secret": "pay_BgVVHyaRkDKAoQJVDNPR_secret_mQHYTu9kWz1eluaPRbIc", "created": "2024-03-01T10:59:44.255Z", "currency": "CZK", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_BgVVHyaRkDKAoQJVDNPR/postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085/pay_BgVVHyaRkDKAoQJVDNPR_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709290784, "expires": 1709294384, "secret": "epk_4ae0f11719b54f94a2170e2ec4fec826" }, "manual_retry_allowed": null, "connector_transaction_id": "P27VSB5K9MBX8N82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "P27VSB5K9MBX8N82", "payment_link": null, "profile_id": "pro_9rma6ktlyR6eBcN16AW3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pXK3IcyuTlLvrUVdT9sC", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T11:14:44.255Z", "fingerprint": null } ```
f95beaa189f17a6e117971a749e2b4595e1e2fc3
- Create a manual capture payment and Cancel it, it should go into processing ``` curl --location 'http://localhost:8080/payments/pay_7RzGoWYbCpeSHynBpytc/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LyWBxSXvkIRgcdWNLamgVQul9tMWq2axdKYlmJSwSFbv0nfDsppaJ6UwSbny0PBm' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` RESPONSE: ``` { "payment_id": "pay_AF6YTcabCeegWRQUWjdZ", "merchant_id": "postman_merchant_GHAction_b6d214c4-4173-4a86-b4e1-52478efba2ca", "status": "processing", "amount": 2134, "net_amount": 2134, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_AF6YTcabCeegWRQUWjdZ_secret_fkz68YL0UTuAJ64Tlji8", "created": "2024-03-01T08:35:04.606Z", "currency": "USD", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "H2GSJ9JB3RJWHST5", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_AF6YTcabCeegWRQUWjdZ_1", "payment_link": null, "profile_id": "pro_KNzwSZXU8MXNySCtfhtI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_kwbRKJxDNAJaEtZkdVFF", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T08:50:04.606Z", "fingerprint": null } ``` - For Refunds Check the `connector_refund_id` and match with Connector psp_reference - Test 3DS payments with normal card and `auth_type` as `three_ds`, 3DS should be triggered ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5dUdESXJ81peNfBZoKwB47YehzdbXBzraGgh69wH0ZtFad9hHHT3isDg7ymJiHZc' \ --data-raw '{ "amount": 2121, "currency": "CZK", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 2121, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "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" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` RESPONSE: ``` { "payment_id": "pay_BgVVHyaRkDKAoQJVDNPR", "merchant_id": "postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085", "status": "requires_customer_action", "amount": 2121, "net_amount": 2121, "amount_capturable": 2121, "amount_received": null, "connector": "adyen", "client_secret": "pay_BgVVHyaRkDKAoQJVDNPR_secret_mQHYTu9kWz1eluaPRbIc", "created": "2024-03-01T10:59:44.255Z", "currency": "CZK", "customer_id": "StripeCustomer", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": null, "country_code": null }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_BgVVHyaRkDKAoQJVDNPR/postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085/pay_BgVVHyaRkDKAoQJVDNPR_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709290784, "expires": 1709294384, "secret": "epk_4ae0f11719b54f94a2170e2ec4fec826" }, "manual_retry_allowed": null, "connector_transaction_id": "P27VSB5K9MBX8N82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "P27VSB5K9MBX8N82", "payment_link": null, "profile_id": "pro_9rma6ktlyR6eBcN16AW3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pXK3IcyuTlLvrUVdT9sC", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T11:14:44.255Z", "fingerprint": null } ```
[ "crates/connector_configs/src/common_config.rs", "crates/connector_configs/src/connector.rs", "crates/connector_configs/src/response_modifier.rs", "crates/connector_configs/src/transformer.rs", "crates/diesel_models/src/enums.rs", "crates/router/src/connector/adyen.rs", "crates/router/src/connector/adye...
juspay/hyperswitch
juspay__hyperswitch-3747
Bug: Storing MIT details in PM table instead of Mandate table Move the connector recurring payment information (`connector_mandate_id`) to the PM table. - Create a column for storing recurring_payment_details in PM table - The connector_mandate_id to be stored against he merchant_connector_id - This columns will hold a simple JSON in the following format `{ <MCA_ID> : <connector_mandate_id>, <MCA_ID> : <connector_mandate_id> . . }`
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4fdf957c842..5b059f255f9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -84,6 +84,7 @@ pub async fn create_payment_method( customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, + connector_mandate_details: Option<serde_json::Value>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { db.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) .await @@ -101,6 +102,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + connector_mandate_details, customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) @@ -187,6 +189,7 @@ pub async fn get_or_insert_payment_method( resp.metadata.clone().map(|val| val.expose()), None, locker_id, + None, ) .await } else { @@ -372,6 +375,7 @@ pub async fn add_payment_method( pm_metadata.cloned(), None, locker_id, + None, ) .await?; } @@ -391,6 +395,7 @@ pub async fn insert_payment_method( pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, + connector_mandate_details: Option<serde_json::Value>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card @@ -408,6 +413,7 @@ pub async fn insert_payment_method( customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await } @@ -1249,12 +1255,16 @@ pub async fn list_payment_methods( }) .await .transpose()?; - + let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage); let payment_type = payment_attempt.as_ref().map(|pa| { let amount = api::Amount::from(pa.amount); let mandate_type = if pa.mandate_id.is_some() { Some(api::MandateTransactionType::RecurringMandateTransaction) - } else if pa.mandate_details.is_some() { + } else if pa.mandate_details.is_some() + || setup_future_usage + .map(|future_usage| future_usage == api_enums::FutureUsage::OffSession) + .unwrap_or(false) + { Some(api::MandateTransactionType::NewMandateTransaction) } else { None diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 943550ef434..c449b76c608 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; use common_utils::{ @@ -42,7 +44,7 @@ where FData: mandate::MandateBehaviour, { match resp.response { - Ok(_) => { + Ok(responses) => { let db = &*state.store; let token_store = state .conf @@ -84,6 +86,22 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; + let connector_mandate_details = if resp.request.get_setup_mandate_details().is_none() + && resp + .request + .get_setup_future_usage() + .map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession) + .unwrap_or(false) + { + add_connector_mandate_details_in_payment_method(responses, connector) + } else { + None + } + .map(|connector_mandate_data| connector_mandate_data.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; + let pm_id = if resp.request.get_setup_future_usage().is_some() && customer_acceptance.is_some() { @@ -194,6 +212,7 @@ where customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await } else { @@ -256,6 +275,7 @@ where resp.metadata.clone().map(|val| val.expose()), customer_acceptance, locker_id, + connector_mandate_details, ) .await } else { @@ -372,6 +392,7 @@ where customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await?; } @@ -623,3 +644,30 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( _ => Ok(None), } } + +fn add_connector_mandate_details_in_payment_method( + resp: types::PaymentsResponseData, + connector: &api::ConnectorData, +) -> Option<storage::PaymentsMandateReference> { + let mut mandate_details = HashMap::new(); + + let connector_mandate_id = match resp { + types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + } => { + if let Some(mandate_ref) = mandate_reference { + mandate_ref.connector_mandate_id.clone() + } else { + None + } + } + _ => None, + }; + + if let Some(mca_id) = connector.merchant_connector_id.clone() { + mandate_details.insert(mca_id, connector_mandate_id); + Some(storage::PaymentsMandateReference(mandate_details)) + } else { + None + } +} diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7005e955dff..9fd7458155a 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -385,6 +385,7 @@ pub async fn save_payout_data_to_locker( None, card_details_encrypted, key_store, + None, ) .await?; diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index a787a4d932c..dee7a8d452f 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -1,9 +1,10 @@ +use std::collections::HashMap; + use api_models::payment_methods; pub use diesel_models::payment_method::{ PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal, TokenizeCoreWorkflow, }; - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum PaymentTokenKind { @@ -52,3 +53,6 @@ impl PaymentTokenData { Self::TemporaryGeneric(GenericTokenData { token }) } } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentsMandateReference(pub HashMap<String, Option<String>>);
2024-03-01T07:56:04Z
## Description store connector_mandate_details in PaymentMethods table, if its a MIT payment, i.e, if its off_session and mandate_type is not present. Also If we do the `LIstPaymentMethodforMerchnats` we get the payment_type as setup_mandate ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create an MA and an MCA with cybersource(cause currently creating a mandate with 0 dollars and just off_session,i.e,MIT is just supported by cybersource) -Make a zero dollar payment, with off_session and no mandate_type ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` ![Screenshot 2024-03-05 at 1 20 20 PM](https://github.com/juspay/hyperswitch/assets/55580080/a2975f96-f1f1-4aeb-8b56-ece43ed23e41) - Do a LIstPaymentMethodforMerchnats , the payment_type = 'setup_mandate' ![Screenshot 2024-03-05 at 1 20 00 PM](https://github.com/juspay/hyperswitch/assets/55580080/6e1538b8-5dc9-4a59-bd51-a85b9b0e3687) - Confirm the payment_with customer_acceptance the card will be save and a mandate would be saved in the database against that payment_method ``` curl --location 'http://localhost:8080/payments/pay_847yeh8NWPsQJRr29528/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` <img width="974" alt="Screenshot 2024-03-05 at 1 22 58 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/8ebddf69-344b-4d17-ab68-6131bc79662a"> -It'll be stored as a HashMap<merchant_connector_id, connector_mandate_id> <img width="1728" alt="Screenshot 2024-03-05 at 1 45 50 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/34305f6b-ff3b-4910-b3eb-9cca2836efe7">
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
- Create an MA and an MCA with cybersource(cause currently creating a mandate with 0 dollars and just off_session,i.e,MIT is just supported by cybersource) -Make a zero dollar payment, with off_session and no mandate_type ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` ![Screenshot 2024-03-05 at 1 20 20 PM](https://github.com/juspay/hyperswitch/assets/55580080/a2975f96-f1f1-4aeb-8b56-ece43ed23e41) - Do a LIstPaymentMethodforMerchnats , the payment_type = 'setup_mandate' ![Screenshot 2024-03-05 at 1 20 00 PM](https://github.com/juspay/hyperswitch/assets/55580080/6e1538b8-5dc9-4a59-bd51-a85b9b0e3687) - Confirm the payment_with customer_acceptance the card will be save and a mandate would be saved in the database against that payment_method ``` curl --location 'http://localhost:8080/payments/pay_847yeh8NWPsQJRr29528/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` <img width="974" alt="Screenshot 2024-03-05 at 1 22 58 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/8ebddf69-344b-4d17-ab68-6131bc79662a"> -It'll be stored as a HashMap<merchant_connector_id, connector_mandate_id> <img width="1728" alt="Screenshot 2024-03-05 at 1 45 50 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/34305f6b-ff3b-4910-b3eb-9cca2836efe7">
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/core/payouts/helpers.rs", "crates/router/src/types/storage/payment_method.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3903
Bug: [BUG] : [Adyen] No configuration for production endpoint ### Bug Description There is no configuration for production endpoint, currently only sbx url is added in config files, also there is no provision to input `prefix` provided by Adyen to be added in each url for all the merchants ### Expected Behavior Configure production url and provision to support appending unique prefix provided by Adyen to each merchant ### Actual Behavior There is no configuration for production endpoint, currently only sbx url is added in config files, also there is no provision to input `prefix` provided by Adyen to be added in each url for all the merchants ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index abe3f6b4e08..760cc2bdd00 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -409,6 +409,10 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility [pm_filters.adyen] +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } online_banking_fpx = { country = "MY", currency = "MYR" } online_banking_thailand = { country = "TH", currency = "THB" } touch_n_go = { country = "MY", currency = "MYR" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dba591ae679..dd755c9dd22 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -174,7 +174,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -193,12 +193,13 @@ oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } + swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 48bb9d33e3f..9c2f25b24ff 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -17,8 +17,8 @@ payout_connector_list = "wise" [connectors] aci.base_url = "https://eu-test.oppwa.com/" -adyen.base_url = "https://checkout-test.adyen.com/" -adyen.secondary_base_url = "https://pal-test.adyen.com/" +adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/" +adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" @@ -189,7 +189,7 @@ google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8723f871c34..5c052e5c85f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -189,7 +189,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/development.toml b/config/development.toml index d69719bd419..824ceaa8eb6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -256,7 +256,7 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban [bank_config.ideal] stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } -adyen = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } +adyen = { banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot, yoursafe" } [bank_config.online_banking_czech_republic] adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" } @@ -314,14 +314,14 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} affirm = { country = "US", currency = "USD" } afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} ideal = { country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8170132bb85..0aaeefb7ae8 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -305,6 +305,11 @@ family_mart = {country = "JP", currency = "JPY"} seicomart = {country = "JP", currency = "JPY"} pay_easy = {country = "JP", currency = "JPY"} boleto = { country = "BR", currency = "BRL" } +ideal = { country = "NL", currency = "EUR" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} + [pm_filters.volt] 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"} diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 45851e4c11b..60c48f3d03c 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -434,6 +434,9 @@ pub enum BankNames { TsbBank, TescoBank, UlsterBank, + Yoursafe, + N26, + NationaleNederlanden, } #[derive( diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 693ea69ff4e..e1f731c25e4 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2506,6 +2508,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 78f6f8d2a76..a463d546ffb 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -124,6 +124,9 @@ key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" + [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index dbb6284fbe9..cf94e1d6222 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2508,6 +2510,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 771ad993ac9..261495e2bfa 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -33,6 +33,8 @@ use crate::{ utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; +const ADYEN_API_VERSION: &str = "v68"; + #[derive(Debug, Clone)] pub struct Adyen; @@ -268,6 +270,23 @@ impl // Not Implemented (R) } +fn build_env_specific_endpoint( + base_url: &str, + test_mode: Option<bool>, + connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, +) -> CustomResult<String, errors::ConnectorError> { + if test_mode.unwrap_or(true) { + Ok(base_url.to_string()) + } else { + let adyen_connector_metadata_object = + transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?; + Ok(base_url.replace( + "{{merchant_endpoint_prefix}}", + &adyen_connector_metadata_object.endpoint_prefix, + )) + } +} + impl services::ConnectorIntegration< api::SetupMandate, @@ -293,10 +312,15 @@ impl fn get_url( &self, - _req: &types::SetupMandateRouterData, + req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( &self, @@ -418,11 +442,15 @@ impl connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}{}/{}/captures", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments", - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/captures", + endpoint, ADYEN_API_VERSION, id )) } fn get_request_body( @@ -560,13 +588,17 @@ impl fn get_url( &self, - _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments/details" + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/details", + endpoint, ADYEN_API_VERSION )) } @@ -681,10 +713,15 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( @@ -785,12 +822,17 @@ impl fn get_url( &self, - _req: &types::PaymentsPreProcessingRouterData, + req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}v69/paymentMethods/balance", - self.base_url(connectors) + "{}{}/paymentMethods/balance", + endpoint, ADYEN_API_VERSION )) } @@ -911,11 +953,16 @@ impl req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}v68/payments/{}/cancels", + let id = req.request.connector_transaction_id.clone(); + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/cancels", + endpoint, ADYEN_API_VERSION, id )) } @@ -991,12 +1038,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCancel>, + req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/declineThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/declineThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1083,12 +1135,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCreate>, + req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/storeDetailAndSubmitThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/storeDetailAndSubmitThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1180,10 +1237,15 @@ impl { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoEligibility>, + req: &types::PayoutsRouterData<api::PoEligibility>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}v68/payments", self.base_url(connectors),)) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_headers( @@ -1277,9 +1339,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/{}", - connectors.adyen.secondary_base_url, + "{}pal/servlet/Payout/{}/{}", + endpoint, + ADYEN_API_VERSION, match req.request.payout_type { storage_enums::PayoutType::Bank | storage_enums::PayoutType::Wallet => "confirmThirdParty".to_string(), @@ -1407,10 +1475,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); - Ok(format!( - "{}v68/payments/{}/refunds", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - connector_payment_id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/refunds", + endpoint, ADYEN_API_VERSION, connector_payment_id )) } @@ -1483,6 +1556,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Adyen { + fn build_request( + &self, + _req: &types::RefundsRouterData<api::RSync>, + _connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Rsync".to_owned(), + connector: "Adyen".to_owned(), + } + .into()) + } } fn get_webhook_object_from_body( @@ -1591,7 +1675,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; // for capture_event, original_reference field will have the authorized payment's PSP reference - if adyen::is_capture_event(&notif.event_code) { + if adyen::is_capture_or_cancel_event(&notif.event_code) { return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( notif @@ -1630,6 +1714,7 @@ impl api::IncomingWebhook for Adyen { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::foreign_from(( notif.event_code, + notif.success, notif.additional_data.dispute_status, ))) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a2fc7cc7ba4..7f20041e1fc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2,7 +2,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; -use common_utils::ext_traits::Encode; +use common_utils::{ext_traits::Encode, pii}; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; @@ -61,6 +61,21 @@ impl<T> }) } } +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct AdyenConnectorMetadataObject { + pub endpoint_prefix: String, +} + +impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject { + 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::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} // Adyen Types Definition // Payments Request and Response Types @@ -230,7 +245,7 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> ) -> Self { match adyen_status { AdyenStatus::AuthenticationFinished => Self::AuthenticationSuccessful, - AdyenStatus::AuthenticationNotRequired => Self::Pending, + AdyenStatus::AuthenticationNotRequired | AdyenStatus::Received => Self::Pending, AdyenStatus::Authorised => match is_manual_capture { true => Self::Authorized, // In case of Automatic capture Authorized is the final status of the payment @@ -245,7 +260,6 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> Some(common_enums::PaymentMethodType::Pix) => Self::AuthenticationPending, _ => Self::Pending, }, - AdyenStatus::Received => Self::Started, #[cfg(feature = "payouts")] AdyenStatus::PayoutConfirmReceived => Self::Started, #[cfg(feature = "payouts")] @@ -281,7 +295,6 @@ pub struct AdyenRefusal { #[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AdyenRedirection { - #[serde(rename = "redirectResult")] pub redirect_result: String, #[serde(rename = "type")] pub type_of_redirection_result: Option<String>, @@ -432,6 +445,7 @@ pub struct Amount { #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] +#[serde(rename_all = "lowercase")] pub enum AdyenPaymentMethod<'a> { AdyenAffirm(Box<PmdForPaymentType>), AdyenCard(Box<AdyenCard>), @@ -1016,6 +1030,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { | enums::BankNames::KrungsriBank | enums::BankNames::KrungThaiBank | enums::BankNames::TheSiamCommercialBank + | enums::BankNames::Yoursafe + | enums::BankNames::N26 + | enums::BankNames::NationaleNederlanden | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Adyen", @@ -1079,8 +1096,9 @@ pub struct AdyenCancelRequest { #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCancelResponse { - psp_reference: String, + payment_psp_reference: String, status: CancelStatus, + reference: String, } #[derive(Default, Debug, Deserialize, Serialize)] @@ -1365,16 +1383,17 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { api_models::enums::BankNames::AbnAmro => Self("1121"), api_models::enums::BankNames::AsnBank => Self("1151"), api_models::enums::BankNames::Bunq => Self("1152"), - api_models::enums::BankNames::Handelsbanken => Self("1153"), api_models::enums::BankNames::Ing => Self("1154"), api_models::enums::BankNames::Knab => Self("1155"), - api_models::enums::BankNames::Moneyou => Self("1156"), + api_models::enums::BankNames::N26 => Self("1156"), + api_models::enums::BankNames::NationaleNederlanden => Self("1157"), api_models::enums::BankNames::Rabobank => Self("1157"), api_models::enums::BankNames::Regiobank => Self("1158"), api_models::enums::BankNames::Revolut => Self("1159"), api_models::enums::BankNames::SnsBank => Self("1159"), api_models::enums::BankNames::TriodosBank => Self("1159"), api_models::enums::BankNames::VanLanschot => Self("1159"), + api_models::enums::BankNames::Yoursafe => Self("1159"), api_models::enums::BankNames::BankAustria => { Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5") } @@ -1419,6 +1438,34 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { } } +pub struct AdyenBankNames<'a>(&'a str); + +impl<'a> TryFrom<&api_enums::BankNames> for AdyenBankNames<'a> { + type Error = Error; + fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> { + Ok(match bank { + api_models::enums::BankNames::AbnAmro => Self("0031"), + api_models::enums::BankNames::AsnBank => Self("0761"), + api_models::enums::BankNames::Bunq => Self("0802"), + api_models::enums::BankNames::Ing => Self("0721"), + api_models::enums::BankNames::Knab => Self("0801"), + api_models::enums::BankNames::N26 => Self("0807"), + api_models::enums::BankNames::NationaleNederlanden => Self("0808"), + api_models::enums::BankNames::Rabobank => Self("0021"), + api_models::enums::BankNames::Regiobank => Self("0771"), + api_models::enums::BankNames::Revolut => Self("0805"), + api_models::enums::BankNames::SnsBank => Self("0751"), + api_models::enums::BankNames::TriodosBank => Self("0511"), + api_models::enums::BankNames::VanLanschot => Self("0161"), + api_models::enums::BankNames::Yoursafe => Self("0806"), + _ => Err(errors::ConnectorError::NotSupported { + message: String::from("BankRedirect"), + connector: "Adyen", + })?, + }) + } +} + impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -2079,10 +2126,12 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)> } } -impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod<'a> { +impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> + for AdyenPaymentMethod<'a> +{ type Error = Error; fn try_from( - bank_redirect_data: &api_models::payments::BankRedirectData, + (bank_redirect_data, test_mode): (&api_models::payments::BankRedirectData, Option<bool>), ) -> Result<Self, Self::Error> { match bank_redirect_data { api_models::payments::BankRedirectData::BancontactCard { @@ -2154,19 +2203,33 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod payment_type: PaymentType::Giropay, }))) } - api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok( - AdyenPaymentMethod::Ideal(Box::new(BankRedirectionWithIssuer { - payment_type: PaymentType::Ideal, - issuer: Some( + api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { + let issuer = if test_mode.unwrap_or(true) { + Some( AdyenTestBankNames::try_from(&bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?)? .0, - ), - })), - ), + ) + } else { + Some( + AdyenBankNames::try_from(&bank_name.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "ideal.bank_name", + }, + )?)? + .0, + ) + }; + Ok(AdyenPaymentMethod::Ideal(Box::new( + BankRedirectionWithIssuer { + payment_type: PaymentType::Ideal, + issuer, + }, + ))) + } api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => { Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new( OnlineBankingCzechRepublicData { @@ -2692,7 +2755,8 @@ impl<'a> let browser_info = get_browser_info(item.router_data)?; let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; - let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; + let payment_method = + AdyenPaymentMethod::try_from((bank_redirect_data, item.router_data.test_mode))?; let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?; let line_items = Some(get_line_items(item)); @@ -2939,15 +3003,6 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { } } -impl From<CancelStatus> for storage_enums::AttemptStatus { - fn from(status: CancelStatus) -> Self { - match status { - CancelStatus::Received => Self::Voided, - CancelStatus::Processing => Self::Pending, - } - } -} - impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> for types::PaymentsCancelRouterData { @@ -2956,14 +3011,16 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> item: types::PaymentsCancelResponseRouterData<AdyenCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - status: item.response.status.into(), + status: enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.payment_psp_reference, + ), 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.reference), incremental_authorization_allowed: None, }), ..item.data @@ -3683,11 +3740,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: item - .response - .merchant_reference - .clone() - .or(Some(item.response.psp_reference)), + connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, }), amount_captured: Some(item.response.amount.value), @@ -3829,7 +3882,9 @@ pub enum WebhookEventCode { Authorisation, Refund, CancelOrRefund, + Cancellation, RefundFailed, + RefundReversed, NotificationOfChargeback, Chargeback, ChargebackReversed, @@ -3846,10 +3901,12 @@ pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool { matches!(event_code, WebhookEventCode::Authorisation) } -pub fn is_capture_event(event_code: &WebhookEventCode) -> bool { +pub fn is_capture_or_cancel_event(event_code: &WebhookEventCode) -> bool { matches!( event_code, - WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + WebhookEventCode::Capture + | WebhookEventCode::CaptureFailed + | WebhookEventCode::Cancellation ) } @@ -3859,6 +3916,7 @@ pub fn is_refund_event(event_code: &WebhookEventCode) -> bool { WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed ) } @@ -3874,31 +3932,66 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool { ) } -impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::IncomingWebhookEvent { - fn foreign_from((code, status): (WebhookEventCode, Option<DisputeStatus>)) -> Self { - match (code, status) { - (WebhookEventCode::Authorisation, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::Refund, _) => Self::RefundSuccess, - (WebhookEventCode::CancelOrRefund, _) => Self::RefundSuccess, - (WebhookEventCode::RefundFailed, _) => Self::RefundFailure, - (WebhookEventCode::NotificationOfChargeback, _) => Self::DisputeOpened, - (WebhookEventCode::Chargeback, None) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Won)) => Self::DisputeWon, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Lost)) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(_)) => Self::DisputeOpened, - (WebhookEventCode::ChargebackReversed, Some(DisputeStatus::Pending)) => { - Self::DisputeChallenged +fn is_success_scenario(is_success: String) -> bool { + is_success.as_str() == "true" +} + +impl ForeignFrom<(WebhookEventCode, String, Option<DisputeStatus>)> + for webhooks::IncomingWebhookEvent +{ + fn foreign_from( + (code, is_success, dispute_status): (WebhookEventCode, String, Option<DisputeStatus>), + ) -> Self { + match code { + WebhookEventCode::Authorisation => { + if is_success_scenario(is_success) { + Self::PaymentIntentSuccess + } else { + Self::PaymentIntentFailure + } + } + WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund => { + if is_success_scenario(is_success) { + Self::RefundSuccess + } else { + Self::RefundFailure + } + } + WebhookEventCode::Cancellation => { + if is_success_scenario(is_success) { + Self::PaymentIntentCancelled + } else { + Self::PaymentIntentCancelFailure + } } - (WebhookEventCode::ChargebackReversed, _) => Self::DisputeWon, - (WebhookEventCode::SecondChargeback, _) => Self::DisputeLost, - (WebhookEventCode::PrearbitrationWon, Some(DisputeStatus::Pending)) => { - Self::DisputeOpened + WebhookEventCode::RefundFailed | WebhookEventCode::RefundReversed => { + Self::RefundFailure } - (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon, - (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost, - (WebhookEventCode::Unknown, _) => Self::EventNotSupported, - (WebhookEventCode::Capture, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::CaptureFailed, _) => Self::PaymentIntentFailure, + WebhookEventCode::NotificationOfChargeback => Self::DisputeOpened, + WebhookEventCode::Chargeback => match dispute_status { + Some(DisputeStatus::Won) => Self::DisputeWon, + Some(DisputeStatus::Lost) | None => Self::DisputeLost, + Some(_) => Self::DisputeOpened, + }, + WebhookEventCode::ChargebackReversed => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeChallenged, + _ => Self::DisputeWon, + }, + WebhookEventCode::SecondChargeback => Self::DisputeLost, + WebhookEventCode::PrearbitrationWon => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeOpened, + _ => Self::DisputeWon, + }, + WebhookEventCode::PrearbitrationLost => Self::DisputeLost, + WebhookEventCode::Capture => { + if is_success_scenario(is_success) { + Self::PaymentIntentCaptureSuccess + } else { + Self::PaymentIntentCaptureFailure + } + } + WebhookEventCode::CaptureFailed => Self::PaymentIntentCaptureFailure, + WebhookEventCode::Unknown => Self::EventNotSupported, } } } @@ -3949,7 +4042,13 @@ impl From<AdyenNotificationRequestItemWH> for Response { psp_reference: notif.psp_reference, merchant_reference: notif.merchant_reference, result_code: match notif.success.as_str() { - "true" => AdyenStatus::Authorised, + "true" => { + if notif.event_code == WebhookEventCode::Cancellation { + AdyenStatus::Cancelled + } else { + AdyenStatus::Authorised + } + } _ => AdyenStatus::Refused, }, amount: Some(Amount { diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d5dd6e813ae..13d522b86cc 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -615,6 +615,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { | api_models::enums::BankNames::Starling | api_models::enums::BankNames::TsbBank | api_models::enums::BankNames::TescoBank + | api_models::enums::BankNames::Yoursafe + | api_models::enums::BankNames::N26 + | api_models::enums::BankNames::NationaleNederlanden | api_models::enums::BankNames::UlsterBank => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 87886c2c861..2b87d64c6ac 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1695,6 +1695,7 @@ pub(crate) fn validate_auth_and_metadata_type( } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(val)?; + adyen::transformers::AdyenConnectorMetadataObject::try_from(connector_meta_data)?; Ok(()) } api_enums::Connector::Airwallex => { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 81dfb7127db..ed96feb2b5e 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -238,7 +238,7 @@ async fn get_tracker_for_sync< operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>> { - let (payment_intent, payment_attempt, currency, amount); + let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( db, @@ -274,6 +274,8 @@ async fn get_tracker_for_sync< ) .await?; + payment_attempt.encoded_data = request.param.clone(); + let attempts = match request.expand_attempts { Some(true) => { Some(db diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2f35958ae6d..aa0d75d609f 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -191,6 +191,10 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30e75c028d5..ce4c4c2a0ef 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5092,7 +5092,10 @@ "starling", "tsb_bank", "tesco_bank", - "ulster_bank" + "ulster_bank", + "yoursafe", + "n26", + "nationale_nederlanden" ] }, "BankRedirectBilling": {
2024-02-29T12:17:48Z
## Description <!-- Describe your changes in detail --> - Add production live endpoint for Adyen - Fix webhooks status mapping - Fix redirection data not getting populated in encoded data - Add Live Bank Names for Ideal - Add Currency, Country config for `klarna, ideal, sofort, paypal` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> - Added configs for Currency, Country for `klarna, ideal, sofort, paypal` - Update payment endpoints for production ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3614 #3903 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - All the flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
7db499d8a9388b9a3674f7fa130bc389151840ec
- All the flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/enums.rs", "crates/connector_configs/toml/development.toml", "crates/conn...
juspay/hyperswitch
juspay__hyperswitch-3614
Bug: [BUG] : [Adyen] Handle redirection response incase of no connector_transaction_id ### Bug Description In Adyen, for certain payment methods that involve redirection, the /payments API call doesn't return a psp_reference (Adyen's transaction ID). In such cases, we need to save the redirectResult field from the redirection response parameter into `encoded_data` field of our payment attempt to facilitate a Psync with proper payment context. However, we have observed that our Psync call lacks context of the Adyen payment because the redirectResult is not stored in the encoded_data ### Expected Behavior Psync for all redirection payments must hit Adyen and retrieve the status of appropriate payment. ### Actual Behavior Psync call has no context of the connector_transaction_id ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1.Create a payment with adyen wechatpay 2.Do a Psync call (the payment status remains to be `requires_customer_action` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/config.example.toml b/config/config.example.toml index abe3f6b4e08..760cc2bdd00 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -409,6 +409,10 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility [pm_filters.adyen] +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } online_banking_fpx = { country = "MY", currency = "MYR" } online_banking_thailand = { country = "TH", currency = "THB" } touch_n_go = { country = "MY", currency = "MYR" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dba591ae679..dd755c9dd22 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -174,7 +174,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -193,12 +193,13 @@ oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } + swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 48bb9d33e3f..9c2f25b24ff 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -17,8 +17,8 @@ payout_connector_list = "wise" [connectors] aci.base_url = "https://eu-test.oppwa.com/" -adyen.base_url = "https://checkout-test.adyen.com/" -adyen.secondary_base_url = "https://pal-test.adyen.com/" +adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/" +adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" @@ -189,7 +189,7 @@ google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8723f871c34..5c052e5c85f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -189,7 +189,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/development.toml b/config/development.toml index d69719bd419..824ceaa8eb6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -256,7 +256,7 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban [bank_config.ideal] stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } -adyen = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } +adyen = { banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot, yoursafe" } [bank_config.online_banking_czech_republic] adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" } @@ -314,14 +314,14 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} affirm = { country = "US", currency = "USD" } afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} ideal = { country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8170132bb85..0aaeefb7ae8 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -305,6 +305,11 @@ family_mart = {country = "JP", currency = "JPY"} seicomart = {country = "JP", currency = "JPY"} pay_easy = {country = "JP", currency = "JPY"} boleto = { country = "BR", currency = "BRL" } +ideal = { country = "NL", currency = "EUR" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} + [pm_filters.volt] 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"} diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 45851e4c11b..60c48f3d03c 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -434,6 +434,9 @@ pub enum BankNames { TsbBank, TescoBank, UlsterBank, + Yoursafe, + N26, + NationaleNederlanden, } #[derive( diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 693ea69ff4e..e1f731c25e4 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2506,6 +2508,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 78f6f8d2a76..a463d546ffb 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -124,6 +124,9 @@ key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" + [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index dbb6284fbe9..cf94e1d6222 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2508,6 +2510,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 771ad993ac9..261495e2bfa 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -33,6 +33,8 @@ use crate::{ utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; +const ADYEN_API_VERSION: &str = "v68"; + #[derive(Debug, Clone)] pub struct Adyen; @@ -268,6 +270,23 @@ impl // Not Implemented (R) } +fn build_env_specific_endpoint( + base_url: &str, + test_mode: Option<bool>, + connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, +) -> CustomResult<String, errors::ConnectorError> { + if test_mode.unwrap_or(true) { + Ok(base_url.to_string()) + } else { + let adyen_connector_metadata_object = + transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?; + Ok(base_url.replace( + "{{merchant_endpoint_prefix}}", + &adyen_connector_metadata_object.endpoint_prefix, + )) + } +} + impl services::ConnectorIntegration< api::SetupMandate, @@ -293,10 +312,15 @@ impl fn get_url( &self, - _req: &types::SetupMandateRouterData, + req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( &self, @@ -418,11 +442,15 @@ impl connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}{}/{}/captures", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments", - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/captures", + endpoint, ADYEN_API_VERSION, id )) } fn get_request_body( @@ -560,13 +588,17 @@ impl fn get_url( &self, - _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments/details" + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/details", + endpoint, ADYEN_API_VERSION )) } @@ -681,10 +713,15 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( @@ -785,12 +822,17 @@ impl fn get_url( &self, - _req: &types::PaymentsPreProcessingRouterData, + req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}v69/paymentMethods/balance", - self.base_url(connectors) + "{}{}/paymentMethods/balance", + endpoint, ADYEN_API_VERSION )) } @@ -911,11 +953,16 @@ impl req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}v68/payments/{}/cancels", + let id = req.request.connector_transaction_id.clone(); + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/cancels", + endpoint, ADYEN_API_VERSION, id )) } @@ -991,12 +1038,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCancel>, + req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/declineThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/declineThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1083,12 +1135,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCreate>, + req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/storeDetailAndSubmitThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/storeDetailAndSubmitThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1180,10 +1237,15 @@ impl { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoEligibility>, + req: &types::PayoutsRouterData<api::PoEligibility>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}v68/payments", self.base_url(connectors),)) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_headers( @@ -1277,9 +1339,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/{}", - connectors.adyen.secondary_base_url, + "{}pal/servlet/Payout/{}/{}", + endpoint, + ADYEN_API_VERSION, match req.request.payout_type { storage_enums::PayoutType::Bank | storage_enums::PayoutType::Wallet => "confirmThirdParty".to_string(), @@ -1407,10 +1475,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); - Ok(format!( - "{}v68/payments/{}/refunds", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - connector_payment_id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/refunds", + endpoint, ADYEN_API_VERSION, connector_payment_id )) } @@ -1483,6 +1556,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Adyen { + fn build_request( + &self, + _req: &types::RefundsRouterData<api::RSync>, + _connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Rsync".to_owned(), + connector: "Adyen".to_owned(), + } + .into()) + } } fn get_webhook_object_from_body( @@ -1591,7 +1675,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; // for capture_event, original_reference field will have the authorized payment's PSP reference - if adyen::is_capture_event(&notif.event_code) { + if adyen::is_capture_or_cancel_event(&notif.event_code) { return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( notif @@ -1630,6 +1714,7 @@ impl api::IncomingWebhook for Adyen { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::foreign_from(( notif.event_code, + notif.success, notif.additional_data.dispute_status, ))) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a2fc7cc7ba4..7f20041e1fc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2,7 +2,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; -use common_utils::ext_traits::Encode; +use common_utils::{ext_traits::Encode, pii}; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; @@ -61,6 +61,21 @@ impl<T> }) } } +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct AdyenConnectorMetadataObject { + pub endpoint_prefix: String, +} + +impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject { + 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::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} // Adyen Types Definition // Payments Request and Response Types @@ -230,7 +245,7 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> ) -> Self { match adyen_status { AdyenStatus::AuthenticationFinished => Self::AuthenticationSuccessful, - AdyenStatus::AuthenticationNotRequired => Self::Pending, + AdyenStatus::AuthenticationNotRequired | AdyenStatus::Received => Self::Pending, AdyenStatus::Authorised => match is_manual_capture { true => Self::Authorized, // In case of Automatic capture Authorized is the final status of the payment @@ -245,7 +260,6 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> Some(common_enums::PaymentMethodType::Pix) => Self::AuthenticationPending, _ => Self::Pending, }, - AdyenStatus::Received => Self::Started, #[cfg(feature = "payouts")] AdyenStatus::PayoutConfirmReceived => Self::Started, #[cfg(feature = "payouts")] @@ -281,7 +295,6 @@ pub struct AdyenRefusal { #[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AdyenRedirection { - #[serde(rename = "redirectResult")] pub redirect_result: String, #[serde(rename = "type")] pub type_of_redirection_result: Option<String>, @@ -432,6 +445,7 @@ pub struct Amount { #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] +#[serde(rename_all = "lowercase")] pub enum AdyenPaymentMethod<'a> { AdyenAffirm(Box<PmdForPaymentType>), AdyenCard(Box<AdyenCard>), @@ -1016,6 +1030,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { | enums::BankNames::KrungsriBank | enums::BankNames::KrungThaiBank | enums::BankNames::TheSiamCommercialBank + | enums::BankNames::Yoursafe + | enums::BankNames::N26 + | enums::BankNames::NationaleNederlanden | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Adyen", @@ -1079,8 +1096,9 @@ pub struct AdyenCancelRequest { #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCancelResponse { - psp_reference: String, + payment_psp_reference: String, status: CancelStatus, + reference: String, } #[derive(Default, Debug, Deserialize, Serialize)] @@ -1365,16 +1383,17 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { api_models::enums::BankNames::AbnAmro => Self("1121"), api_models::enums::BankNames::AsnBank => Self("1151"), api_models::enums::BankNames::Bunq => Self("1152"), - api_models::enums::BankNames::Handelsbanken => Self("1153"), api_models::enums::BankNames::Ing => Self("1154"), api_models::enums::BankNames::Knab => Self("1155"), - api_models::enums::BankNames::Moneyou => Self("1156"), + api_models::enums::BankNames::N26 => Self("1156"), + api_models::enums::BankNames::NationaleNederlanden => Self("1157"), api_models::enums::BankNames::Rabobank => Self("1157"), api_models::enums::BankNames::Regiobank => Self("1158"), api_models::enums::BankNames::Revolut => Self("1159"), api_models::enums::BankNames::SnsBank => Self("1159"), api_models::enums::BankNames::TriodosBank => Self("1159"), api_models::enums::BankNames::VanLanschot => Self("1159"), + api_models::enums::BankNames::Yoursafe => Self("1159"), api_models::enums::BankNames::BankAustria => { Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5") } @@ -1419,6 +1438,34 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { } } +pub struct AdyenBankNames<'a>(&'a str); + +impl<'a> TryFrom<&api_enums::BankNames> for AdyenBankNames<'a> { + type Error = Error; + fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> { + Ok(match bank { + api_models::enums::BankNames::AbnAmro => Self("0031"), + api_models::enums::BankNames::AsnBank => Self("0761"), + api_models::enums::BankNames::Bunq => Self("0802"), + api_models::enums::BankNames::Ing => Self("0721"), + api_models::enums::BankNames::Knab => Self("0801"), + api_models::enums::BankNames::N26 => Self("0807"), + api_models::enums::BankNames::NationaleNederlanden => Self("0808"), + api_models::enums::BankNames::Rabobank => Self("0021"), + api_models::enums::BankNames::Regiobank => Self("0771"), + api_models::enums::BankNames::Revolut => Self("0805"), + api_models::enums::BankNames::SnsBank => Self("0751"), + api_models::enums::BankNames::TriodosBank => Self("0511"), + api_models::enums::BankNames::VanLanschot => Self("0161"), + api_models::enums::BankNames::Yoursafe => Self("0806"), + _ => Err(errors::ConnectorError::NotSupported { + message: String::from("BankRedirect"), + connector: "Adyen", + })?, + }) + } +} + impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -2079,10 +2126,12 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)> } } -impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod<'a> { +impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> + for AdyenPaymentMethod<'a> +{ type Error = Error; fn try_from( - bank_redirect_data: &api_models::payments::BankRedirectData, + (bank_redirect_data, test_mode): (&api_models::payments::BankRedirectData, Option<bool>), ) -> Result<Self, Self::Error> { match bank_redirect_data { api_models::payments::BankRedirectData::BancontactCard { @@ -2154,19 +2203,33 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod payment_type: PaymentType::Giropay, }))) } - api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok( - AdyenPaymentMethod::Ideal(Box::new(BankRedirectionWithIssuer { - payment_type: PaymentType::Ideal, - issuer: Some( + api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { + let issuer = if test_mode.unwrap_or(true) { + Some( AdyenTestBankNames::try_from(&bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?)? .0, - ), - })), - ), + ) + } else { + Some( + AdyenBankNames::try_from(&bank_name.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "ideal.bank_name", + }, + )?)? + .0, + ) + }; + Ok(AdyenPaymentMethod::Ideal(Box::new( + BankRedirectionWithIssuer { + payment_type: PaymentType::Ideal, + issuer, + }, + ))) + } api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => { Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new( OnlineBankingCzechRepublicData { @@ -2692,7 +2755,8 @@ impl<'a> let browser_info = get_browser_info(item.router_data)?; let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; - let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; + let payment_method = + AdyenPaymentMethod::try_from((bank_redirect_data, item.router_data.test_mode))?; let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?; let line_items = Some(get_line_items(item)); @@ -2939,15 +3003,6 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { } } -impl From<CancelStatus> for storage_enums::AttemptStatus { - fn from(status: CancelStatus) -> Self { - match status { - CancelStatus::Received => Self::Voided, - CancelStatus::Processing => Self::Pending, - } - } -} - impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> for types::PaymentsCancelRouterData { @@ -2956,14 +3011,16 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> item: types::PaymentsCancelResponseRouterData<AdyenCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - status: item.response.status.into(), + status: enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.payment_psp_reference, + ), 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.reference), incremental_authorization_allowed: None, }), ..item.data @@ -3683,11 +3740,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: item - .response - .merchant_reference - .clone() - .or(Some(item.response.psp_reference)), + connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, }), amount_captured: Some(item.response.amount.value), @@ -3829,7 +3882,9 @@ pub enum WebhookEventCode { Authorisation, Refund, CancelOrRefund, + Cancellation, RefundFailed, + RefundReversed, NotificationOfChargeback, Chargeback, ChargebackReversed, @@ -3846,10 +3901,12 @@ pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool { matches!(event_code, WebhookEventCode::Authorisation) } -pub fn is_capture_event(event_code: &WebhookEventCode) -> bool { +pub fn is_capture_or_cancel_event(event_code: &WebhookEventCode) -> bool { matches!( event_code, - WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + WebhookEventCode::Capture + | WebhookEventCode::CaptureFailed + | WebhookEventCode::Cancellation ) } @@ -3859,6 +3916,7 @@ pub fn is_refund_event(event_code: &WebhookEventCode) -> bool { WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed ) } @@ -3874,31 +3932,66 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool { ) } -impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::IncomingWebhookEvent { - fn foreign_from((code, status): (WebhookEventCode, Option<DisputeStatus>)) -> Self { - match (code, status) { - (WebhookEventCode::Authorisation, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::Refund, _) => Self::RefundSuccess, - (WebhookEventCode::CancelOrRefund, _) => Self::RefundSuccess, - (WebhookEventCode::RefundFailed, _) => Self::RefundFailure, - (WebhookEventCode::NotificationOfChargeback, _) => Self::DisputeOpened, - (WebhookEventCode::Chargeback, None) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Won)) => Self::DisputeWon, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Lost)) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(_)) => Self::DisputeOpened, - (WebhookEventCode::ChargebackReversed, Some(DisputeStatus::Pending)) => { - Self::DisputeChallenged +fn is_success_scenario(is_success: String) -> bool { + is_success.as_str() == "true" +} + +impl ForeignFrom<(WebhookEventCode, String, Option<DisputeStatus>)> + for webhooks::IncomingWebhookEvent +{ + fn foreign_from( + (code, is_success, dispute_status): (WebhookEventCode, String, Option<DisputeStatus>), + ) -> Self { + match code { + WebhookEventCode::Authorisation => { + if is_success_scenario(is_success) { + Self::PaymentIntentSuccess + } else { + Self::PaymentIntentFailure + } + } + WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund => { + if is_success_scenario(is_success) { + Self::RefundSuccess + } else { + Self::RefundFailure + } + } + WebhookEventCode::Cancellation => { + if is_success_scenario(is_success) { + Self::PaymentIntentCancelled + } else { + Self::PaymentIntentCancelFailure + } } - (WebhookEventCode::ChargebackReversed, _) => Self::DisputeWon, - (WebhookEventCode::SecondChargeback, _) => Self::DisputeLost, - (WebhookEventCode::PrearbitrationWon, Some(DisputeStatus::Pending)) => { - Self::DisputeOpened + WebhookEventCode::RefundFailed | WebhookEventCode::RefundReversed => { + Self::RefundFailure } - (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon, - (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost, - (WebhookEventCode::Unknown, _) => Self::EventNotSupported, - (WebhookEventCode::Capture, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::CaptureFailed, _) => Self::PaymentIntentFailure, + WebhookEventCode::NotificationOfChargeback => Self::DisputeOpened, + WebhookEventCode::Chargeback => match dispute_status { + Some(DisputeStatus::Won) => Self::DisputeWon, + Some(DisputeStatus::Lost) | None => Self::DisputeLost, + Some(_) => Self::DisputeOpened, + }, + WebhookEventCode::ChargebackReversed => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeChallenged, + _ => Self::DisputeWon, + }, + WebhookEventCode::SecondChargeback => Self::DisputeLost, + WebhookEventCode::PrearbitrationWon => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeOpened, + _ => Self::DisputeWon, + }, + WebhookEventCode::PrearbitrationLost => Self::DisputeLost, + WebhookEventCode::Capture => { + if is_success_scenario(is_success) { + Self::PaymentIntentCaptureSuccess + } else { + Self::PaymentIntentCaptureFailure + } + } + WebhookEventCode::CaptureFailed => Self::PaymentIntentCaptureFailure, + WebhookEventCode::Unknown => Self::EventNotSupported, } } } @@ -3949,7 +4042,13 @@ impl From<AdyenNotificationRequestItemWH> for Response { psp_reference: notif.psp_reference, merchant_reference: notif.merchant_reference, result_code: match notif.success.as_str() { - "true" => AdyenStatus::Authorised, + "true" => { + if notif.event_code == WebhookEventCode::Cancellation { + AdyenStatus::Cancelled + } else { + AdyenStatus::Authorised + } + } _ => AdyenStatus::Refused, }, amount: Some(Amount { diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d5dd6e813ae..13d522b86cc 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -615,6 +615,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { | api_models::enums::BankNames::Starling | api_models::enums::BankNames::TsbBank | api_models::enums::BankNames::TescoBank + | api_models::enums::BankNames::Yoursafe + | api_models::enums::BankNames::N26 + | api_models::enums::BankNames::NationaleNederlanden | api_models::enums::BankNames::UlsterBank => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 87886c2c861..2b87d64c6ac 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1695,6 +1695,7 @@ pub(crate) fn validate_auth_and_metadata_type( } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(val)?; + adyen::transformers::AdyenConnectorMetadataObject::try_from(connector_meta_data)?; Ok(()) } api_enums::Connector::Airwallex => { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 81dfb7127db..ed96feb2b5e 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -238,7 +238,7 @@ async fn get_tracker_for_sync< operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>> { - let (payment_intent, payment_attempt, currency, amount); + let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( db, @@ -274,6 +274,8 @@ async fn get_tracker_for_sync< ) .await?; + payment_attempt.encoded_data = request.param.clone(); + let attempts = match request.expand_attempts { Some(true) => { Some(db diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2f35958ae6d..aa0d75d609f 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -191,6 +191,10 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30e75c028d5..ce4c4c2a0ef 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5092,7 +5092,10 @@ "starling", "tsb_bank", "tesco_bank", - "ulster_bank" + "ulster_bank", + "yoursafe", + "n26", + "nationale_nederlanden" ] }, "BankRedirectBilling": {
2024-02-29T12:17:48Z
## Description <!-- Describe your changes in detail --> - Add production live endpoint for Adyen - Fix webhooks status mapping - Fix redirection data not getting populated in encoded data - Add Live Bank Names for Ideal - Add Currency, Country config for `klarna, ideal, sofort, paypal` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> - Added configs for Currency, Country for `klarna, ideal, sofort, paypal` - Update payment endpoints for production ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3614 #3903 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - All the flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
7db499d8a9388b9a3674f7fa130bc389151840ec
- All the flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/enums.rs", "crates/connector_configs/toml/development.toml", "crates/conn...
juspay/hyperswitch
juspay__hyperswitch-3895
Bug: refactor: change create and update role apis to respond with role info
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index aee2b3fb66c..0d42d1de7d6 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -3,7 +3,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse, - RoleInfoResponse, RoleInfoWithPermissionsResponse, UpdateRoleRequest, + RoleInfoResponse, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse, + UpdateRoleRequest, }, AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest, @@ -21,5 +22,6 @@ common_utils::impl_misc_api_event_type!( UpdateRoleRequest, ListRolesResponse, RoleInfoResponse, - GetRoleFromTokenResponse + GetRoleFromTokenResponse, + RoleInfoWithGroupsResponse ); diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index c3d534f8860..6aa226cd933 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -57,14 +57,18 @@ pub async fn create_role( state: AppState, user_from_token: UserFromToken, req: role_api::CreateRoleRequest, -) -> UserResponse<()> { +) -> UserResponse<role_api::RoleInfoWithGroupsResponse> { let now = common_utils::date_time::now(); - let role_name = RoleName::new(req.role_name)?.get_role_name(); + let role_name = RoleName::new(req.role_name)?; - if req.groups.is_empty() { - return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("Role groups cannot be empty"); - } + utils::user_role::validate_role_groups(&req.groups)?; + utils::user_role::validate_role_name( + &state, + &role_name, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await?; if matches!(req.role_scope, RoleScope::Organization) && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN @@ -73,19 +77,11 @@ pub async fn create_role( .attach_printable("Non org admin user creating org level role"); } - utils::user_role::is_role_name_already_present_for_merchant( - &state, - &role_name, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await?; - - state + let role = state .store .insert_role(RoleNew { role_id: generate_id_with_default_len("role"), - role_name, + role_name: role_name.get_role_name(), merchant_id: user_from_token.merchant_id, org_id: user_from_token.org_id, groups: req.groups, @@ -98,7 +94,14 @@ pub async fn create_role( .await .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; - Ok(ApplicationResponse::StatusOk) + Ok(ApplicationResponse::Json( + role_api::RoleInfoWithGroupsResponse { + groups: role.groups, + role_id: role.role_id, + role_name: role.role_name, + role_scope: role.scope, + }, + )) } // TODO: To be deprecated once groups are stable @@ -260,15 +263,11 @@ pub async fn update_role( user_from_token: UserFromToken, req: role_api::UpdateRoleRequest, role_id: &str, -) -> UserResponse<()> { - let role_name = req - .role_name - .map(RoleName::new) - .transpose()? - .map(RoleName::get_role_name); +) -> UserResponse<role_api::RoleInfoWithGroupsResponse> { + let role_name = req.role_name.map(RoleName::new).transpose()?; if let Some(ref role_name) = role_name { - utils::user_role::is_role_name_already_present_for_merchant( + utils::user_role::validate_role_name( &state, role_name, &user_from_token.merchant_id, @@ -277,6 +276,10 @@ pub async fn update_role( .await?; } + if let Some(ref groups) = req.groups { + utils::user_role::validate_role_groups(groups)?; + } + let role_info = roles::RoleInfo::from_role_id( &state, role_id, @@ -290,23 +293,16 @@ pub async fn update_role( && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN { return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("Non org admin user creating org level role"); + .attach_printable("Non org admin user changing org level role"); } - if let Some(ref groups) = req.groups { - if groups.is_empty() { - return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("role groups cannot be empty"); - } - } - - state + let updated_role = state .store .update_role_by_role_id( role_id, RoleUpdate::UpdateDetails { groups: req.groups, - role_name, + role_name: role_name.map(RoleName::get_role_name), last_modified_at: common_utils::date_time::now(), last_modified_by: user_from_token.user_id, }, @@ -316,5 +312,12 @@ pub async fn update_role( blacklist::insert_role_in_blacklist(&state, role_id).await?; - Ok(ApplicationResponse::StatusOk) + Ok(ApplicationResponse::Json( + role_api::RoleInfoWithGroupsResponse { + groups: updated_role.groups, + role_id: updated_role.role_id, + role_name: updated_role.role_name, + role_scope: updated_role.scope, + }, + )) } diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index 9accf094ea4..568af6e19fd 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -26,7 +26,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::OrganizationManage, ], role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(), - role_name: "Internal Admin".to_string(), + role_name: "internal_admin".to_string(), scope: RoleScope::Organization, is_invitable: false, is_deletable: false, @@ -46,7 +46,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), - role_name: "Internal View Only".to_string(), + role_name: "internal_view_only".to_string(), scope: RoleScope::Organization, is_invitable: false, is_deletable: false, @@ -73,7 +73,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::OrganizationManage, ], role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - role_name: "Organization Admin".to_string(), + role_name: "organization_admin".to_string(), scope: RoleScope::Organization, is_invitable: false, is_deletable: false, @@ -100,7 +100,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), - role_name: "Admin".to_string(), + role_name: "admin".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, @@ -120,7 +120,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), - role_name: "View Only".to_string(), + role_name: "view_only".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, @@ -139,7 +139,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), - role_name: "IAM".to_string(), + role_name: "iam".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, @@ -159,7 +159,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), - role_name: "Developer".to_string(), + role_name: "developer".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, @@ -180,7 +180,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), - role_name: "Operator".to_string(), + role_name: "operator".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, @@ -198,7 +198,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), - role_name: "Customer Support".to_string(), + role_name: "customer_support".to_string(), scope: RoleScope::Organization, is_invitable: true, is_deletable: true, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 8ae65ce86e0..bb83b82f2da 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,10 +1,12 @@ use api_models::user_role as user_role_api; +use common_enums::PermissionGroup; use error_stack::ResultExt; use crate::{ core::errors::{UserErrors, UserResult}, routes::AppState, - services::authorization::permissions::Permission, + services::authorization::{permissions::Permission, roles}, + types::domain, }; impl From<Permission> for user_role_api::Permission { @@ -40,23 +42,44 @@ impl From<Permission> for user_role_api::Permission { } } -pub async fn is_role_name_already_present_for_merchant( +pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { + if groups.is_empty() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Role groups cannot be empty"); + } + + if groups.contains(&PermissionGroup::OrganizationManage) { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Organization manage group cannot be added to role"); + } + + Ok(()) +} + +pub async fn validate_role_name( state: &AppState, - role_name: &str, + role_name: &domain::RoleName, merchant_id: &str, org_id: &str, ) -> UserResult<()> { - let role_name_list: Vec<String> = state + let role_name_str = role_name.clone().get_role_name(); + + let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES + .iter() + .any(|(_, role_info)| role_info.get_role_name() == role_name_str); + + // TODO: Create and use find_by_role_name to make this efficient + let is_present_in_custom_roles = state .store .list_all_roles(merchant_id, org_id) .await .change_context(UserErrors::InternalServerError)? .iter() - .map(|role| role.role_name.to_owned()) - .collect(); + .any(|role| role.role_name == role_name_str); - if role_name_list.contains(&role_name.to_string()) { + if is_present_in_predefined_roles || is_present_in_custom_roles { return Err(UserErrors::RoleNameAlreadyExists.into()); } + Ok(()) }
2024-02-29T10:55:41Z
## Description <!-- Describe your changes in detail --> This PR modifies create and update role APIs. The APIs will now respond with the role created/updated respectively. This PR also changes the names of predefined roles to snake case. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #3895 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create role - `organization_manage` cannot be sent in groups. - `role_name` should not be present in any other roles that merchant has access to. - Non `org_admin` won't be able to create a role with `role_scope` as `organization` - `groups` should not be empty. ``` curl --location 'http://localhost:8080/user/role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "role_name": "admin", "groups": ["users_manage"], "role_scope": "organization" }' ``` - Response: ``` { "role_id": "role_KLw0K0psguhVX8FhvIuv", "groups": [ "users_manage" ], "role_name": "admin1", "role_scope": "organization" } ``` 2. Update role - `organization_manage` cannot be sent in groups. - `role_name` should not be present in any other roles that merchant has access to. - Non `org_admin` won't be able to update a role with `role_scope` as `organization` - `groups` should not be empty. ``` curl --location 'http://localhost:8080/user/role/role_KLw0K0psguhVX8FhvIuv' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "groups": ["users_view"] }' ``` - Response: ``` { "role_id": "role_KLw0K0psguhVX8FhvIuv", "groups": [ "users_view" ], "role_name": "admin1", "role_scope": "organization" } ```
de7f400c07d85b97340255556b39383648a0fd9f
1. Create role - `organization_manage` cannot be sent in groups. - `role_name` should not be present in any other roles that merchant has access to. - Non `org_admin` won't be able to create a role with `role_scope` as `organization` - `groups` should not be empty. ``` curl --location 'http://localhost:8080/user/role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "role_name": "admin", "groups": ["users_manage"], "role_scope": "organization" }' ``` - Response: ``` { "role_id": "role_KLw0K0psguhVX8FhvIuv", "groups": [ "users_manage" ], "role_name": "admin1", "role_scope": "organization" } ``` 2. Update role - `organization_manage` cannot be sent in groups. - `role_name` should not be present in any other roles that merchant has access to. - Non `org_admin` won't be able to update a role with `role_scope` as `organization` - `groups` should not be empty. ``` curl --location 'http://localhost:8080/user/role/role_KLw0K0psguhVX8FhvIuv' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "groups": ["users_view"] }' ``` - Response: ``` { "role_id": "role_KLw0K0psguhVX8FhvIuv", "groups": [ "users_view" ], "role_name": "admin1", "role_scope": "organization" } ```
[ "crates/api_models/src/events/user_role.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/services/authorization/roles/predefined_roles.rs", "crates/router/src/utils/user_role.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3893
Bug: [FEATURE] [PLACETOPAY] Connector audit ### Feature Description Connector placetopay needs to be audited. ### Possible Implementation Connector placetopay needs to be audited. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/placetopay.rs b/crates/router/src/connector/placetopay.rs index 81255f450e5..c28fed1fede 100644 --- a/crates/router/src/connector/placetopay.rs +++ b/crates/router/src/connector/placetopay.rs @@ -119,8 +119,8 @@ impl ConnectorValidation for Placetopay { ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { - enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::Automatic + enums::CaptureMethod::Automatic => Ok(()), + enums::CaptureMethod::Manual | enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(utils::construct_not_supported_error_report( capture_method, @@ -615,7 +615,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() - .method(services::Method::Get) + .method(services::Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index f1c054b960b..e5dedf6ded0 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -206,30 +206,43 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuthType { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum PlacetopayStatus { +pub enum PlacetopayTransactionStatus { Ok, Failed, Approved, + // ApprovedPartial, + // PartialExpired, Rejected, Pending, PendingValidation, PendingProcess, + // Refunded, + // Reversed, + Error, + // Unknown, + // Manual, + // Dispute, + //The statuses that are commented out are awaiting clarification on the connector. } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayStatusResponse { - status: PlacetopayStatus, + status: PlacetopayTransactionStatus, } -impl From<PlacetopayStatus> for enums::AttemptStatus { - fn from(item: PlacetopayStatus) -> Self { +impl From<PlacetopayTransactionStatus> for enums::AttemptStatus { + fn from(item: PlacetopayTransactionStatus) -> Self { match item { - PlacetopayStatus::Approved | PlacetopayStatus::Ok => Self::Authorized, - PlacetopayStatus::Failed | PlacetopayStatus::Rejected => Self::Failure, - PlacetopayStatus::Pending - | PlacetopayStatus::PendingValidation - | PlacetopayStatus::PendingProcess => Self::Authorizing, + PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => { + Self::Charged + } + PlacetopayTransactionStatus::Failed + | PlacetopayTransactionStatus::Rejected + | PlacetopayTransactionStatus::Error => Self::Failure, + PlacetopayTransactionStatus::Pending + | PlacetopayTransactionStatus::PendingValidation + | PlacetopayTransactionStatus::PendingProcess => Self::Pending, } } } @@ -239,6 +252,7 @@ impl From<PlacetopayStatus> for enums::AttemptStatus { pub struct PlacetopayPaymentsResponse { status: PlacetopayStatusResponse, internal_reference: u64, + authorization: Option<String>, } impl<F, T> @@ -263,7 +277,11 @@ impl<F, T> ), redirection_data: None, mandate_reference: None, - connector_metadata: None, + connector_metadata: item + .response + .authorization + .clone() + .map(|authorization| serde_json::json!(authorization)), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, @@ -281,55 +299,90 @@ pub struct PlacetopayRefundRequest { auth: PlacetopayAuth, internal_reference: u64, action: PlacetopayNextAction, + authorization: Option<String>, } impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; - let internal_reference = item - .request - .connector_transaction_id - .parse::<u64>() - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let action = PlacetopayNextAction::Refund; - - Ok(Self { - auth, - internal_reference, - action, - }) + if item.request.refund_amount == item.request.payment_amount { + let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; + + let internal_reference = item + .request + .connector_transaction_id + .parse::<u64>() + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let action = PlacetopayNextAction::Reverse; + let authorization = match item.request.connector_metadata.clone() { + Some(metadata) => metadata.as_str().map(|auth| auth.to_string()), + None => None, + }; + Ok(Self { + auth, + internal_reference, + action, + authorization, + }) + } else { + Err(errors::ConnectorError::NotSupported { + message: "Partial Refund".to_string(), + connector: "placetopay", + } + .into()) + } } } impl From<PlacetopayRefundStatus> for enums::RefundStatus { fn from(item: PlacetopayRefundStatus) -> Self { match item { - PlacetopayRefundStatus::Refunded => Self::Success, - PlacetopayRefundStatus::Failed | PlacetopayRefundStatus::Rejected => Self::Failure, - PlacetopayRefundStatus::Pending | PlacetopayRefundStatus::PendingProcess => { - Self::Pending - } + PlacetopayRefundStatus::Ok + | PlacetopayRefundStatus::Approved + | PlacetopayRefundStatus::Refunded => Self::Success, + PlacetopayRefundStatus::Failed + | PlacetopayRefundStatus::Rejected + | PlacetopayRefundStatus::Error => Self::Failure, + PlacetopayRefundStatus::Pending + | PlacetopayRefundStatus::PendingProcess + | PlacetopayRefundStatus::PendingValidation => Self::Pending, } } } -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct PlacetopayRefundResponse { - status: PlacetopayRefundStatus, - internal_reference: u64, -} - #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayRefundStatus { - Refunded, - Rejected, + Ok, Failed, + Approved, + // ApprovedPartial, + // PartialExpired, + Rejected, Pending, + PendingValidation, PendingProcess, + Refunded, + // Reversed, + Error, + // Unknown, + // Manual, + // Dispute, + //The statuses that are commented out are awaiting clarification on the connector. +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlacetopayRefundStatusResponse { + status: PlacetopayRefundStatus, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlacetopayRefundResponse { + status: PlacetopayRefundStatusResponse, + internal_reference: u64, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, PlacetopayRefundResponse>> @@ -342,7 +395,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PlacetopayRefundResp Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.internal_reference.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: enums::RefundStatus::from(item.response.status.status), }), ..item.data }) @@ -383,7 +436,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, PlacetopayRefundRespon Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.internal_reference.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: enums::RefundStatus::from(item.response.status.status), }), ..item.data }) @@ -447,6 +500,7 @@ pub struct PlacetopayNextActionRequest { #[serde(rename_all = "camelCase")] pub enum PlacetopayNextAction { Refund, + Reverse, Void, Process, Checkout,
2024-02-29T10:28:24Z
## Description <!-- Describe your changes in detail --> - The authorization field retrieved during payments for Placetopay is now utilized in refund requests. The following features have been removed as they are not supported by the connector: - Manual authorization - Partial refunds ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3893 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The following flows need to be tested for connector placetopay: 1. Authorization(Auto-capture) Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` Response: ```json { "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "merchant_id": "merchant_1707896273", "status": "succeeded", "amount": 320320, "net_amount": 320320, "amount_capturable": 0, "amount_received": 320320, "connector": "placetopay", "client_secret": "pay_6Ra7qnW72e498RBrNgGs_secret_bqPRBHD9bFu6HzOzwkR1", "created": "2024-03-01T09:31:37.556Z", "currency": "COP", "customer_id": "deepanshu", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2837", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411077", "card_extended_bin": "41107700", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "deepanshu", "created_at": 1709285497, "expires": 1709289097, "secret": "epk_f80f7b586ab64a1eae89501b68c09d00" }, "manual_retry_allowed": false, "connector_transaction_id": "1598433361", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_aAoX3JP7KaSPBqGXewox", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T09:46:37.556Z", "fingerprint": null } ``` 2. Authorization(Manual capture) Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` Response: ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "HE_03", "reason": "manual is not supported by placetopay" } } ``` 3. Refunds Request: ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "refund_type": "instant" }' ``` Response: ```json { "refund_id": "ref_dFvFk3gvAKMsWEyWq81d", "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "amount": 320320, "currency": "COP", "status": "succeeded", "reason": null, "metadata": null, "error_message": null, "error_code": null, "created_at": "2024-03-01T09:31:45.539Z", "updated_at": "2024-03-01T09:31:45.539Z", "connector": "placetopay", "profile_id": "pro_aAoX3JP7KaSPBqGXewox", "merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd" } ``` 3. Partial Refunds Request: ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_T5RoR7gNvWAilXweIUOo", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ```json { "error": { "type": "invalid_request", "message": "Refund failed while processing with connector. Retry refund", "code": "CE_06" } } ```
f132527490a7d8cd8469573d8e6856f33974959f
The following flows need to be tested for connector placetopay: 1. Authorization(Auto-capture) Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` Response: ```json { "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "merchant_id": "merchant_1707896273", "status": "succeeded", "amount": 320320, "net_amount": 320320, "amount_capturable": 0, "amount_received": 320320, "connector": "placetopay", "client_secret": "pay_6Ra7qnW72e498RBrNgGs_secret_bqPRBHD9bFu6HzOzwkR1", "created": "2024-03-01T09:31:37.556Z", "currency": "COP", "customer_id": "deepanshu", "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2837", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411077", "card_extended_bin": "41107700", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "deepanshu", "created_at": 1709285497, "expires": 1709289097, "secret": "epk_f80f7b586ab64a1eae89501b68c09d00" }, "manual_retry_allowed": false, "connector_transaction_id": "1598433361", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_aAoX3JP7KaSPBqGXewox", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-03-01T09:46:37.556Z", "fingerprint": null } ``` 2. Authorization(Manual capture) Request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount":320320, "currency": "COP", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "deepanshu", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4110770010002837", "card_exp_month": "02", "card_exp_year": "26", "card_holder_name": "joseph", "card_cvc": "837" } }, "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", "ip_address": "127.2.2.0" } }' ``` Response: ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "HE_03", "reason": "manual is not supported by placetopay" } } ``` 3. Refunds Request: ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "refund_type": "instant" }' ``` Response: ```json { "refund_id": "ref_dFvFk3gvAKMsWEyWq81d", "payment_id": "pay_6Ra7qnW72e498RBrNgGs", "amount": 320320, "currency": "COP", "status": "succeeded", "reason": null, "metadata": null, "error_message": null, "error_code": null, "created_at": "2024-03-01T09:31:45.539Z", "updated_at": "2024-03-01T09:31:45.539Z", "connector": "placetopay", "profile_id": "pro_aAoX3JP7KaSPBqGXewox", "merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd" } ``` 3. Partial Refunds Request: ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_T5RoR7gNvWAilXweIUOo", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ```json { "error": { "type": "invalid_request", "message": "Refund failed while processing with connector. Retry refund", "code": "CE_06" } } ```
[ "crates/router/src/connector/placetopay.rs", "crates/router/src/connector/placetopay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3801
Bug: [REFACTOR] provide an identifier for the api key in the expiry reminder email ### Issue Description: Currently, our system sends out reminder emails to merchants when their API key is about to expire. However, since merchants can create multiple API keys, the email lacks clarity on which specific API key is expiring. ### Proposed Solution: Refactor the api key expiry reminder workflow to include the name and prefix of the expiring API key in email. This will help merchants easily identify which API key requires attention without confusion. ### Details: Update the email template to include the following information: API Key Name along with Prefix in below format - `API_KEY_NAME [PREFIX]` ### Reference: Check `ApiKeyExpiryTrackingData` type in https://github.com/juspay/hyperswitch/blob/2c95dcd19778726f476b219271dc42da182088af/crates/diesel_models/src/api_keys.rs
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs index 1875fc4dc51..7676e20d224 100644 --- a/crates/diesel_models/src/api_keys.rs +++ b/crates/diesel_models/src/api_keys.rs @@ -141,6 +141,8 @@ mod diesel_impl { pub struct ApiKeyExpiryTrackingData { pub key_id: String, pub merchant_id: String, + pub api_key_name: String, + pub prefix: String, pub api_key_expiry: Option<PrimitiveDateTime>, // Days on which email reminder about api_key expiry has to be sent, prior to it's expiry. pub expiry_reminder_days: Vec<u8>, diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 7d2069618d5..a2fcacb3b3d 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -207,6 +207,8 @@ pub async fn add_api_key_expiry_task( let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), + api_key_name: api_key.name.clone(), + prefix: api_key.prefix.clone(), // We need API key expiry too, because we need to decide on the schedule_time in // execute_workflow() where we won't be having access to the Api key object. api_key_expiry: api_key.expires_at, @@ -369,6 +371,8 @@ pub async fn update_api_key_expiry_task( let updated_tracking_data = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), + api_key_name: api_key.name.clone(), + prefix: api_key.prefix.clone(), api_key_expiry: api_key.expires_at, expiry_reminder_days, }; diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html index 1865ae38141..772602d71e7 100644 --- a/crates/router/src/services/email/assets/api_key_expiry_reminder.html +++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html @@ -43,20 +43,7 @@ cellpadding="0" cellspacing="0" > - <tr> - <td - class="spacer-lg" - style=" - -premailer-height: 75; - -premailer-width: 100%; - line-height: 30px; - margin: 0 auto; - padding: 0; - " - height="75" - width="100%" - ></td> - </tr> + <tr> <td class="spacer-lg" @@ -96,13 +83,13 @@ line-height: 36px; margin: 0 auto; padding: 0; - text-align: center; + text-align: left; " align="center" > <p style="font-size: 18px">Dear Merchant,</p> <span style="font-size: 18px"> - It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted + It has come to our attention that your API key, <b>{api_key_name}</b> (<code>{prefix}*****</code>) </code> will expire in {expires_in} days. To ensure uninterrupted access to our platform and continued smooth operation of your services, we kindly request that you take the necessary actions as soon as possible. </span> @@ -118,39 +105,11 @@ margin: 0 auto; padding: 0; " - width="100%" - ></td> - </tr> - - <tr> - <td - class="spacer-sm" - style=" - -premailer-height: 20; - -premailer-width: 100%; - line-height: 10px; - margin: 0 auto; - padding: 0; - " height="20" width="100%" ></td> </tr> - <tr> - <td - class="spacer-lg" - style=" - -premailer-height: 75; - -premailer-width: 100%; - line-height: 30px; - margin: 0 auto; - padding: 0; - " - height="75" - width="100%" - ></td> - </tr> <tr> <td class="headline" @@ -162,7 +121,7 @@ line-height: 36px; margin: 0 auto; padding: 0; - text-align: center; + text-align: left; " align="center" > @@ -184,20 +143,7 @@ width="100%" ></td> </tr> - <tr> - <td - class="spacer-lg" - style=" - -premailer-height: 75; - -premailer-width: 100%; - line-height: 30px; - margin: 0 auto; - padding: 0; - " - height="75" - width="100%" - ></td> - </tr> + </table> </div> </body> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index fa1eecbaab8..2fbe7d606e5 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -50,6 +50,8 @@ pub enum EmailBody { }, ApiKeyExpiryReminder { expires_in: u8, + api_key_name: String, + prefix: String, }, } @@ -128,8 +130,14 @@ Email : {user_email} (note: This is an auto generated email. Use merchant email for any further communications)", ), - EmailBody::ApiKeyExpiryReminder { expires_in } => format!( + EmailBody::ApiKeyExpiryReminder { + expires_in, + api_key_name, + prefix, + } => format!( include_str!("assets/api_key_expiry_reminder.html"), + api_key_name = api_key_name, + prefix = prefix, expires_in = expires_in, ), } @@ -441,6 +449,8 @@ pub struct ApiKeyExpiryReminder { pub recipient_email: domain::UserEmail, pub subject: &'static str, pub expires_in: u8, + pub api_key_name: String, + pub prefix: String, } #[async_trait::async_trait] @@ -450,6 +460,8 @@ impl EmailData for ApiKeyExpiryReminder { let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { expires_in: self.expires_in, + api_key_name: self.api_key_name.clone(), + prefix: self.prefix.clone(), }); Ok(EmailContents { diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index e9e1f323708..c5914810108 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -54,6 +54,10 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { let retry_count = process.retry_count; + let api_key_name = tracking_data.api_key_name.clone(); + + let prefix = tracking_data.prefix.clone(); + let expires_in = tracking_data .expiry_reminder_days .get( @@ -69,6 +73,9 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { })?, subject: "API Key Expiry Notice", expires_in: *expires_in, + api_key_name, + prefix, + }; state
2024-02-29T08:09:49Z
## Description <!-- Describe your changes in detail --> Refactored the api key expiry reminder workflow to include the name and prefix of the expiring API key in the email ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes the issue #3801 If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> It fixes #3801 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a merchant account 2. Create an api key with expiry somewhat closer to 7 days from current time in UTC format. 3. You should get an email something like below once api key expiry is exactly 7 days from current time ![image](https://github.com/juspay/hyperswitch/assets/70657455/41d40ff4-7db4-4d22-bfdd-8eabd2a35f41)
6b078fa339b5404f7c730322bc8597cd1104ec15
1. Create a merchant account 2. Create an api key with expiry somewhat closer to 7 days from current time in UTC format. 3. You should get an email something like below once api key expiry is exactly 7 days from current time ![image](https://github.com/juspay/hyperswitch/assets/70657455/41d40ff4-7db4-4d22-bfdd-8eabd2a35f41)
[ "crates/diesel_models/src/api_keys.rs", "crates/router/src/core/api_keys.rs", "crates/router/src/services/email/assets/api_key_expiry_reminder.html", "crates/router/src/services/email/types.rs", "crates/router/src/workflows/api_key_expiry.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3887
Bug: [Analytics] - Disputes fix psql
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs index 9bdac332295..eae8281a99d 100644 --- a/crates/diesel_models/src/dispute.rs +++ b/crates/diesel_models/src/dispute.rs @@ -29,6 +29,7 @@ pub struct DisputeNew { pub evidence: Option<Secret<serde_json::Value>>, pub profile_id: Option<String>, pub merchant_connector_id: Option<String>, + pub dispute_amount: i64, } #[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable)] @@ -59,6 +60,7 @@ pub struct Dispute { pub evidence: Secret<serde_json::Value>, pub profile_id: Option<String>, pub merchant_connector_id: Option<String>, + pub dispute_amount: i64, } #[derive(Debug)] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 9e72d8dc21d..9db9f8c2d43 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -295,6 +295,7 @@ diesel::table! { profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, + dispute_amount -> Int8, } } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index ef313b62228..9ec8de21f94 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -352,7 +352,7 @@ pub async fn get_or_update_dispute_object( let dispute_id = generate_id(consts::ID_LENGTH, "dp"); let new_dispute = diesel_models::dispute::DisputeNew { dispute_id, - amount: dispute_details.amount, + amount: dispute_details.amount.clone(), currency: dispute_details.currency, dispute_stage: dispute_details.dispute_stage, dispute_status: event_type @@ -374,6 +374,7 @@ pub async fn get_or_update_dispute_object( profile_id: Some(business_profile.profile_id.clone()), evidence: None, merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0), }; state .store diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 0c34123b6f3..b0d0594c013 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -180,6 +180,7 @@ impl DisputeInterface for MockDb { profile_id: dispute.profile_id, evidence, merchant_connector_id: dispute.merchant_connector_id, + dispute_amount: dispute.dispute_amount, }; locked_disputes.push(new_dispute.clone()); @@ -414,6 +415,7 @@ mod tests { evidence: Some(Secret::from(Value::String("evidence".into()))), profile_id: None, merchant_connector_id: None, + dispute_amount: 1040, } } diff --git a/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql new file mode 100644 index 00000000000..e89bb9a356b --- /dev/null +++ b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql @@ -0,0 +1,17 @@ +-- This file should undo anything in `up.sql` +-- Drop the new column +ALTER TABLE dispute +DROP COLUMN IF EXISTS dispute_amount; + +-- Optionally, if you want to revert the UPDATE statement as well (assuming you have a backup) +-- You can restore the original data from the backup or use the old values to update the table + +-- For example, if you have a backup and want to revert the changes made by the UPDATE statement +-- You can replace the data with the backup data or the original values +-- For demonstration purposes, we're assuming you have a backup table named dispute_backup + +-- Restore the original values from the backup or any other source +-- UPDATE dispute +-- SET dispute_amount = backup.dispute_amount +-- FROM dispute_backup AS backup +-- WHERE dispute.id = backup.id; diff --git a/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql new file mode 100644 index 00000000000..b56ffc4fe9c --- /dev/null +++ b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql @@ -0,0 +1,8 @@ +-- Your SQL goes here +-- Add the new column with a default value +ALTER TABLE dispute +ADD COLUMN dispute_amount BIGINT NOT NULL DEFAULT 0; + +-- Update existing rows to set the default value based on the integer equivalent of the amount column +UPDATE dispute +SET dispute_amount = CAST(amount AS BIGINT);
2024-02-29T08:01:39Z
## Description adding dispute_amount column as int type because amount in dispute table is of string type on which we cannot have aggregation for analytics ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->run the migration, one column will be added to dispute table called dispute_amount as BIGINT type and will backfill from amount column which is string type
0936b02ade7f57eaa0213c4f4422bff7c9bb4de2
run the migration, one column will be added to dispute table called dispute_amount as BIGINT type and will backfill from amount column which is string type
[ "crates/diesel_models/src/dispute.rs", "crates/diesel_models/src/schema.rs", "crates/router/src/core/webhooks.rs", "crates/router/src/db/dispute.rs", "migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql", "migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-3744
Bug: Setup future usage validations for recurring payments (CIT and MIT) Setup Future Usage parameter to be used for saving PM for both CIT and MIT recurring payments. - If on-session, save card in locker and add PM for future payments based on (payment success + customer acceptance) - If off-session, save card in locker set up for MITs with the connector and add MIT details to the PM table based on (customer acceptance) - If customer acceptance is null in both cases, do not save the PM NOTE: setup_future_usage : on-session will now come from the payments/create request and conveys the merchant's intention of saving it for future CIT payments. In payments/confirm call the customer acceptance of the on-session request will be provided.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9a3afd2f0ff..d48be04b763 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -348,9 +348,12 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, - /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server usually and the customer_acceptance sub object is usually passed by the SDK or client + /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, + /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + pub customer_acceptance: Option<CustomerAcceptance>, + /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 6b25b692c12..dfa98634e27 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1143,8 +1143,8 @@ pub enum IntentStatus { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { - #[default] OffSession, + #[default] OnSession, } diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index b4478f84ee9..fa22a4e57d5 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -113,6 +113,16 @@ impl From<ApiCustomerAcceptance> for CustomerAcceptance { } } +impl From<CustomerAcceptance> for ApiCustomerAcceptance { + fn from(value: CustomerAcceptance) -> Self { + Self { + acceptance_type: value.acceptance_type.into(), + accepted_at: value.accepted_at, + online: value.online.map(|d| d.into()), + } + } +} + impl From<ApiAcceptanceType> for AcceptanceType { fn from(value: ApiAcceptanceType) -> Self { match value { @@ -121,6 +131,14 @@ impl From<ApiAcceptanceType> for AcceptanceType { } } } +impl From<AcceptanceType> for ApiAcceptanceType { + fn from(value: AcceptanceType) -> Self { + match value { + AcceptanceType::Online => Self::Online, + AcceptanceType::Offline => Self::Offline, + } + } +} impl From<ApiOnlineMandate> for OnlineMandate { fn from(value: ApiOnlineMandate) -> Self { @@ -130,6 +148,14 @@ impl From<ApiOnlineMandate> for OnlineMandate { } } } +impl From<OnlineMandate> for ApiOnlineMandate { + fn from(value: OnlineMandate) -> Self { + Self { + ip_address: value.ip_address, + user_agent: value.user_agent, + } + } +} impl CustomerAcceptance { pub fn get_ip_address(&self) -> Option<String> { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index ec3bb7e4299..d07a8814c88 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -495,4 +495,5 @@ pub trait MandateBehaviour { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>; + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>; } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..4fdf957c842 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -81,6 +81,7 @@ pub async fn create_payment_method( locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { @@ -100,6 +101,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) .await @@ -183,6 +185,7 @@ pub async fn get_or_insert_payment_method( &merchant_account.merchant_id, customer_id, resp.metadata.clone().map(|val| val.expose()), + None, locker_id, ) .await @@ -367,6 +370,7 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + None, locker_id, ) .await?; @@ -385,6 +389,7 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp @@ -400,6 +405,7 @@ pub async fn insert_payment_method( locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7e8fa2ae44d..88a437a087e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -15,7 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI use api_models::{self, enums, payments::HeaderPayload}; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; @@ -2049,6 +2049,7 @@ where pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, + pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub confirm: Option<bool>, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index d7d122c3252..cc2540aa221 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -99,7 +99,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; Ok(mandate::mandate_procedure( @@ -131,7 +130,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, - is_mandate, )) .await; @@ -294,6 +292,9 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { self.mandate_id = new_mandate_id; } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } pub async fn authorize_preprocessing_steps<F: Clone>( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 3f43204b986..71d43989336 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -98,7 +98,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -107,7 +107,6 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; mandate::mandate_procedure( @@ -234,8 +233,6 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; - let is_mandate = resp.request.setup_mandate_details.is_some(); - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -244,7 +241,6 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, - is_mandate, )) .await?; @@ -320,7 +316,6 @@ impl types::SetupMandateRouterData { ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -329,7 +324,6 @@ impl types::SetupMandateRouterData { merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; let mandate = state @@ -430,6 +424,9 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData { fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> { self.setup_mandate_details.as_ref() } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } impl TryFrom<types::SetupMandateRequestData> for types::PaymentMethodTokenizationData { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d711bca7ab4..f0a5e38cca4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -825,16 +825,6 @@ fn validate_new_mandate_request( .clone() .get_required_value("mandate_data")?; - if api_enums::FutureUsage::OnSession - == req - .setup_future_usage - .get_required_value("setup_future_usage")? - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` must be `off_session` for mandates".into() - }))? - }; - // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance @@ -3855,3 +3845,17 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr Ok(()) } } + +// This function validates the mandate_data with its setup_future_usage +pub fn validate_mandate_data_and_future_usage( + setup_future_usages: Option<api_enums::FutureUsage>, + mandate_details_present: bool, +) -> Result<(), errors::ApiErrorResponse> { + if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` must be `off_session` for mandates".into(), + }) + } else { + Ok(()) + } +} diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index caca29d8e2a..a38c7bbdd3c 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 097b7ab40e1..1b09e9abce5 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -155,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index e9d520e4abc..4a488a07eb3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -200,6 +200,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), 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 f7e7598cf73..395f8e59dbc 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -215,6 +215,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -239,6 +245,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance: None, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5c47c3f323e..9117f406040 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -361,6 +361,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + let customer_acceptance = request.customer_acceptance.clone().map(From::from); helpers::validate_card_data( request @@ -461,6 +462,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> sm }); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let n_request_payment_method_data = request .payment_method_data .as_ref() @@ -539,6 +546,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 11ab21b891d..2c07f4249e8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -281,6 +281,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; + let mandate_details_present = payment_attempt.mandate_details.is_some(); + + helpers::validate_mandate_data_and_future_usage( + request.setup_future_usage, + mandate_details_present, + )?; // connector mandate reference update history let mandate_id = request .mandate_id @@ -355,6 +361,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(MandateData::from); + let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -368,6 +376,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .apply_additional_payment_data(additional_payment_data) }); + let amount = payment_attempt.get_total_amount().into(); let payment_data = PaymentData { flow: PhantomData, @@ -379,6 +388,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 281ffdd06f7..a1416ea1908 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -143,6 +143,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 966600a5498..ed3eda8832b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -167,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> email: None, mandate_id: None, mandate_connector: None, + customer_acceptance: None, token: None, setup_mandate: None, address: payments::PaymentAddress { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 2ca413b73aa..650fef7e1bf 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: payment_attempt.payment_token.clone(), address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index aa622b3558b..70f04ed364d 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -414,6 +414,7 @@ async fn get_tracker_for_sync< }), mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index cd73df26ff3..7661ee515d9 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -349,7 +349,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); - + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -363,7 +368,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; - + let customer_acceptance = request.customer_acceptance.clone().map(From::from); let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -379,6 +384,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_connector, token, setup_mandate, + customer_acceptance, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), 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 24292507c0e..96cbf9fb9db 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -120,6 +120,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { billing: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1f793e2e185..943550ef434 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,6 +1,9 @@ use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ + ext_traits::{Encode, ValueExt}, + pii, +}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -34,7 +37,6 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, - is_mandate: bool, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -67,16 +69,24 @@ where } else { None }; - let future_usage_validation = resp + + let mandate_data_customer_acceptance = resp .request - .get_setup_future_usage() - .map(|future_usage| { - (future_usage == storage_enums::FutureUsage::OffSession && is_mandate) - || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate) - }) - .unwrap_or(false); + .get_setup_mandate_details() + .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); + + let customer_acceptance = resp + .request + .get_customer_acceptance() + .or(mandate_data_customer_acceptance.clone().map(From::from)) + .map(|ca| ca.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; - let pm_id = if future_usage_validation { + let pm_id = if resp.request.get_setup_future_usage().is_some() + && customer_acceptance.is_some() + { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), @@ -181,6 +191,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) @@ -243,6 +254,7 @@ where &merchant_account.merchant_id, &customer.customer_id, resp.metadata.clone().map(|val| val.expose()), + customer_acceptance, locker_id, ) .await @@ -357,6 +369,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7c7bac80cf0..8ccab155c69 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1141,6 +1141,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz | Some(RequestIncrementalAuthorization::Default) ), metadata: additional_data.payment_data.payment_intent.metadata, + customer_acceptance: payment_data.customer_acceptance, }) } } @@ -1436,6 +1437,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index fcd2569ea99..7005e955dff 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -382,6 +382,7 @@ pub async fn save_payout_data_to_locker( Some(stored_resp.card_reference), &merchant_account.merchant_id, None, + None, card_details_encrypted, key_store, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 07691879d4a..106872fb43f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -24,7 +24,7 @@ pub use api_models::{ use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::Serialize; @@ -408,6 +408,7 @@ pub struct PaymentsAuthorizeData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, + pub customer_acceptance: Option<CustomerAcceptance>, pub setup_mandate_details: Option<MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, @@ -584,6 +585,7 @@ pub struct SetupMandateRequestData { pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, + pub customer_acceptance: Option<CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -1423,6 +1425,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, + customer_acceptance: data.request.customer_acceptance.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 221d16a8b46..4f3d6f7e296 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -50,6 +50,7 @@ impl VerifyConnectorData { related_transaction_id: None, statement_descriptor_suffix: None, request_incremental_authorization: false, + customer_acceptance: None, } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index d3f8147fb26..5c4660805fb 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -72,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 12812a70857..55f9f6b4b6b 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -170,6 +170,7 @@ impl AdyenTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index d24e20cd660..93043f37c9b 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index a9d81d2bb62..7dd70d86695 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -70,6 +70,7 @@ impl CashtocodeTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 7a872ecb585..b1fffb302cb 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -98,6 +98,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index d61a93c8b82..6eaf514db21 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 8415be949a0..4702012597e 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -97,6 +97,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 8f749a0b2ff..83380f76073 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -915,6 +915,7 @@ impl Default for PaymentAuthorizeType { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index c5b12a0b0b2..ba946b296bf 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -106,6 +106,7 @@ impl WorldlineTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 293bfc85a7c..1a3e71f38c0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -12529,6 +12529,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -12880,6 +12888,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -13286,6 +13302,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -14277,6 +14301,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "browser_info": { "allOf": [ { diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index b66df150887..9570f0f0b8d 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 80dad74bb60..0bf892efdf5 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json index 08e62dca6e9..a515beb2661 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json index 21c079e0ad0..eecdf810746 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json index 1ec9a829a48..660ef06c518 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 93e802128f2..40a78911a9a 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json index e3d19912b79..d152474c374 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index e37391b78b5..43eb0c9cc12 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json index 056b9269a29..d0320b09975 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json index 1d85fee7356..fe4adccda47 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json index 73457bf3197..aaa993e4eef 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index ffda1aef2d7..050f353af53 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 97cce7936c4..63d1eeba233 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json index 7aeaf601cc6..2cbfe4a20f1 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json index 824bfb49230..7201fa121be 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json index efa17534b1d..f5da408b2f3 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json @@ -45,6 +45,14 @@ "wallet": { "paypal_redirect": {} } + }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } } } }, diff --git a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 57d625e7c39..fbbd60339e9 100644 --- a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 93bcc23194f..9d0fac32c1f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 3ffbe03a605..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -98,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index 9df18b5e886..61f007ede68 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "shipping": { "address": { "line1": "1467", @@ -86,12 +94,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json index eda0801c9cc..78d949505f4 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json @@ -23,9 +23,7 @@ "confirm": true, "business_label": "default", "capture_method": "automatic", - "connector": [ - "stripe" - ], + "connector": ["stripe"], "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", @@ -55,6 +53,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { @@ -85,12 +91,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json index 20b99223ac4..43515f184b5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json @@ -52,6 +52,7 @@ } } }, + "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", @@ -73,7 +74,14 @@ } } }, - "setup_future_usage": "off_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" + } + }, "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", @@ -90,14 +98,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json index 785122a83c5..beeb5b3983f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json @@ -71,12 +71,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5a51941cf64..1b1757b9a49 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "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" + } + }, "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", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json index 2019bae8790..2ac0cacfb99 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json index 4f02f7b6809..150106cfded 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json index 988bc4b800b..d73166871cd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index 60e56bb581c..6a9836d232c 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 6d1bc5e0a0d..a3e0f52b8d7 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index a5c9391cf74..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json index ac22dac750c..cc330f3c8f7 100644 --- a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 7afc6d61c49..fd84bcaadb5 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json index 778f8872687..2f295eba3a8 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json @@ -51,6 +51,14 @@ "java_script_enabled": true, "ip_address": "127.0.0.1" }, + "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" + } + }, "order_details": [ { "amount": 6540, @@ -60,6 +68,7 @@ ] } }, + "url": { "raw": "{{baseUrl}}/payments/:id/confirm", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json index ee354325323..bed15211eea 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_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" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json index 01fa4013653..91a932b12d9 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json index ee354325323..aa51751ae1e 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json @@ -31,7 +31,15 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "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" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467",
2024-02-29T07:39:24Z
## Description store customer_acceptance in the payment_methods table and some changes to setup_future_usage - setup_future_usage should be inferred from the create and if passed in confirm should override the one in create - If customer_acceptance is passed then only the card will be saved on hyper switch's end ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? -make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
5eff9d47d3e53d380ef792a8fbdf06ecf78d3d16
-make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
[ "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/data_models/src/mandates.rs", "crates/router/src/core/mandate.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/flows/authorize_flow.rs", "crate...
juspay/hyperswitch
juspay__hyperswitch-3745
Bug: Customer Acceptance to be moved out of Mandate object Customer acceptance needs to be a property of the Payment Method instead of Mandate. - Move the Customer Acceptance object outside of the Mandate object in the payments request - Store the Customer Acceptance data in the PM table
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9a3afd2f0ff..d48be04b763 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -348,9 +348,12 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, - /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server usually and the customer_acceptance sub object is usually passed by the SDK or client + /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, + /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + pub customer_acceptance: Option<CustomerAcceptance>, + /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 6b25b692c12..dfa98634e27 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1143,8 +1143,8 @@ pub enum IntentStatus { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { - #[default] OffSession, + #[default] OnSession, } diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index b4478f84ee9..fa22a4e57d5 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -113,6 +113,16 @@ impl From<ApiCustomerAcceptance> for CustomerAcceptance { } } +impl From<CustomerAcceptance> for ApiCustomerAcceptance { + fn from(value: CustomerAcceptance) -> Self { + Self { + acceptance_type: value.acceptance_type.into(), + accepted_at: value.accepted_at, + online: value.online.map(|d| d.into()), + } + } +} + impl From<ApiAcceptanceType> for AcceptanceType { fn from(value: ApiAcceptanceType) -> Self { match value { @@ -121,6 +131,14 @@ impl From<ApiAcceptanceType> for AcceptanceType { } } } +impl From<AcceptanceType> for ApiAcceptanceType { + fn from(value: AcceptanceType) -> Self { + match value { + AcceptanceType::Online => Self::Online, + AcceptanceType::Offline => Self::Offline, + } + } +} impl From<ApiOnlineMandate> for OnlineMandate { fn from(value: ApiOnlineMandate) -> Self { @@ -130,6 +148,14 @@ impl From<ApiOnlineMandate> for OnlineMandate { } } } +impl From<OnlineMandate> for ApiOnlineMandate { + fn from(value: OnlineMandate) -> Self { + Self { + ip_address: value.ip_address, + user_agent: value.user_agent, + } + } +} impl CustomerAcceptance { pub fn get_ip_address(&self) -> Option<String> { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index ec3bb7e4299..d07a8814c88 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -495,4 +495,5 @@ pub trait MandateBehaviour { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>; + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>; } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..4fdf957c842 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -81,6 +81,7 @@ pub async fn create_payment_method( locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { @@ -100,6 +101,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) .await @@ -183,6 +185,7 @@ pub async fn get_or_insert_payment_method( &merchant_account.merchant_id, customer_id, resp.metadata.clone().map(|val| val.expose()), + None, locker_id, ) .await @@ -367,6 +370,7 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + None, locker_id, ) .await?; @@ -385,6 +389,7 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp @@ -400,6 +405,7 @@ pub async fn insert_payment_method( locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7e8fa2ae44d..88a437a087e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -15,7 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI use api_models::{self, enums, payments::HeaderPayload}; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; @@ -2049,6 +2049,7 @@ where pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, + pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub confirm: Option<bool>, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index d7d122c3252..cc2540aa221 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -99,7 +99,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; Ok(mandate::mandate_procedure( @@ -131,7 +130,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, - is_mandate, )) .await; @@ -294,6 +292,9 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { self.mandate_id = new_mandate_id; } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } pub async fn authorize_preprocessing_steps<F: Clone>( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 3f43204b986..71d43989336 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -98,7 +98,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -107,7 +107,6 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; mandate::mandate_procedure( @@ -234,8 +233,6 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; - let is_mandate = resp.request.setup_mandate_details.is_some(); - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -244,7 +241,6 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, - is_mandate, )) .await?; @@ -320,7 +316,6 @@ impl types::SetupMandateRouterData { ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -329,7 +324,6 @@ impl types::SetupMandateRouterData { merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; let mandate = state @@ -430,6 +424,9 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData { fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> { self.setup_mandate_details.as_ref() } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } impl TryFrom<types::SetupMandateRequestData> for types::PaymentMethodTokenizationData { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d711bca7ab4..f0a5e38cca4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -825,16 +825,6 @@ fn validate_new_mandate_request( .clone() .get_required_value("mandate_data")?; - if api_enums::FutureUsage::OnSession - == req - .setup_future_usage - .get_required_value("setup_future_usage")? - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` must be `off_session` for mandates".into() - }))? - }; - // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance @@ -3855,3 +3845,17 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr Ok(()) } } + +// This function validates the mandate_data with its setup_future_usage +pub fn validate_mandate_data_and_future_usage( + setup_future_usages: Option<api_enums::FutureUsage>, + mandate_details_present: bool, +) -> Result<(), errors::ApiErrorResponse> { + if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` must be `off_session` for mandates".into(), + }) + } else { + Ok(()) + } +} diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index caca29d8e2a..a38c7bbdd3c 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 097b7ab40e1..1b09e9abce5 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -155,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index e9d520e4abc..4a488a07eb3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -200,6 +200,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), 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 f7e7598cf73..395f8e59dbc 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -215,6 +215,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -239,6 +245,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance: None, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5c47c3f323e..9117f406040 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -361,6 +361,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + let customer_acceptance = request.customer_acceptance.clone().map(From::from); helpers::validate_card_data( request @@ -461,6 +462,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> sm }); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let n_request_payment_method_data = request .payment_method_data .as_ref() @@ -539,6 +546,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 11ab21b891d..2c07f4249e8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -281,6 +281,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; + let mandate_details_present = payment_attempt.mandate_details.is_some(); + + helpers::validate_mandate_data_and_future_usage( + request.setup_future_usage, + mandate_details_present, + )?; // connector mandate reference update history let mandate_id = request .mandate_id @@ -355,6 +361,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(MandateData::from); + let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -368,6 +376,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .apply_additional_payment_data(additional_payment_data) }); + let amount = payment_attempt.get_total_amount().into(); let payment_data = PaymentData { flow: PhantomData, @@ -379,6 +388,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 281ffdd06f7..a1416ea1908 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -143,6 +143,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 966600a5498..ed3eda8832b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -167,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> email: None, mandate_id: None, mandate_connector: None, + customer_acceptance: None, token: None, setup_mandate: None, address: payments::PaymentAddress { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 2ca413b73aa..650fef7e1bf 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: payment_attempt.payment_token.clone(), address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index aa622b3558b..70f04ed364d 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -414,6 +414,7 @@ async fn get_tracker_for_sync< }), mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index cd73df26ff3..7661ee515d9 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -349,7 +349,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); - + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -363,7 +368,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; - + let customer_acceptance = request.customer_acceptance.clone().map(From::from); let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -379,6 +384,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_connector, token, setup_mandate, + customer_acceptance, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), 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 24292507c0e..96cbf9fb9db 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -120,6 +120,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { billing: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1f793e2e185..943550ef434 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,6 +1,9 @@ use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ + ext_traits::{Encode, ValueExt}, + pii, +}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -34,7 +37,6 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, - is_mandate: bool, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -67,16 +69,24 @@ where } else { None }; - let future_usage_validation = resp + + let mandate_data_customer_acceptance = resp .request - .get_setup_future_usage() - .map(|future_usage| { - (future_usage == storage_enums::FutureUsage::OffSession && is_mandate) - || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate) - }) - .unwrap_or(false); + .get_setup_mandate_details() + .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); + + let customer_acceptance = resp + .request + .get_customer_acceptance() + .or(mandate_data_customer_acceptance.clone().map(From::from)) + .map(|ca| ca.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; - let pm_id = if future_usage_validation { + let pm_id = if resp.request.get_setup_future_usage().is_some() + && customer_acceptance.is_some() + { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), @@ -181,6 +191,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) @@ -243,6 +254,7 @@ where &merchant_account.merchant_id, &customer.customer_id, resp.metadata.clone().map(|val| val.expose()), + customer_acceptance, locker_id, ) .await @@ -357,6 +369,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7c7bac80cf0..8ccab155c69 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1141,6 +1141,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz | Some(RequestIncrementalAuthorization::Default) ), metadata: additional_data.payment_data.payment_intent.metadata, + customer_acceptance: payment_data.customer_acceptance, }) } } @@ -1436,6 +1437,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index fcd2569ea99..7005e955dff 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -382,6 +382,7 @@ pub async fn save_payout_data_to_locker( Some(stored_resp.card_reference), &merchant_account.merchant_id, None, + None, card_details_encrypted, key_store, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 07691879d4a..106872fb43f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -24,7 +24,7 @@ pub use api_models::{ use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::Serialize; @@ -408,6 +408,7 @@ pub struct PaymentsAuthorizeData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, + pub customer_acceptance: Option<CustomerAcceptance>, pub setup_mandate_details: Option<MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, @@ -584,6 +585,7 @@ pub struct SetupMandateRequestData { pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, + pub customer_acceptance: Option<CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -1423,6 +1425,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, + customer_acceptance: data.request.customer_acceptance.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 221d16a8b46..4f3d6f7e296 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -50,6 +50,7 @@ impl VerifyConnectorData { related_transaction_id: None, statement_descriptor_suffix: None, request_incremental_authorization: false, + customer_acceptance: None, } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index d3f8147fb26..5c4660805fb 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -72,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 12812a70857..55f9f6b4b6b 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -170,6 +170,7 @@ impl AdyenTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index d24e20cd660..93043f37c9b 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index a9d81d2bb62..7dd70d86695 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -70,6 +70,7 @@ impl CashtocodeTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 7a872ecb585..b1fffb302cb 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -98,6 +98,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index d61a93c8b82..6eaf514db21 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 8415be949a0..4702012597e 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -97,6 +97,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 8f749a0b2ff..83380f76073 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -915,6 +915,7 @@ impl Default for PaymentAuthorizeType { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index c5b12a0b0b2..ba946b296bf 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -106,6 +106,7 @@ impl WorldlineTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 293bfc85a7c..1a3e71f38c0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -12529,6 +12529,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -12880,6 +12888,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -13286,6 +13302,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -14277,6 +14301,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "browser_info": { "allOf": [ { diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index b66df150887..9570f0f0b8d 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 80dad74bb60..0bf892efdf5 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json index 08e62dca6e9..a515beb2661 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "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" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json index 21c079e0ad0..eecdf810746 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json index 1ec9a829a48..660ef06c518 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 93e802128f2..40a78911a9a 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json index e3d19912b79..d152474c374 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index e37391b78b5..43eb0c9cc12 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json index 056b9269a29..d0320b09975 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json index 1d85fee7356..fe4adccda47 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json index 73457bf3197..aaa993e4eef 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index ffda1aef2d7..050f353af53 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 97cce7936c4..63d1eeba233 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json index 7aeaf601cc6..2cbfe4a20f1 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json index 824bfb49230..7201fa121be 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json index efa17534b1d..f5da408b2f3 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json @@ -45,6 +45,14 @@ "wallet": { "paypal_redirect": {} } + }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } } } }, diff --git a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 57d625e7c39..fbbd60339e9 100644 --- a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 93bcc23194f..9d0fac32c1f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 3ffbe03a605..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -98,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index 9df18b5e886..61f007ede68 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "shipping": { "address": { "line1": "1467", @@ -86,12 +94,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json index eda0801c9cc..78d949505f4 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json @@ -23,9 +23,7 @@ "confirm": true, "business_label": "default", "capture_method": "automatic", - "connector": [ - "stripe" - ], + "connector": ["stripe"], "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", @@ -55,6 +53,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { @@ -85,12 +91,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json index 20b99223ac4..43515f184b5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json @@ -52,6 +52,7 @@ } } }, + "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", @@ -73,7 +74,14 @@ } } }, - "setup_future_usage": "off_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" + } + }, "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", @@ -90,14 +98,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json index 785122a83c5..beeb5b3983f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json @@ -71,12 +71,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5a51941cf64..1b1757b9a49 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "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" + } + }, "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", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json index 2019bae8790..2ac0cacfb99 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json index 4f02f7b6809..150106cfded 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json index 988bc4b800b..d73166871cd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "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" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index 60e56bb581c..6a9836d232c 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 6d1bc5e0a0d..a3e0f52b8d7 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "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/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index a5c9391cf74..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json index ac22dac750c..cc330f3c8f7 100644 --- a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 7afc6d61c49..fd84bcaadb5 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json index 778f8872687..2f295eba3a8 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json @@ -51,6 +51,14 @@ "java_script_enabled": true, "ip_address": "127.0.0.1" }, + "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" + } + }, "order_details": [ { "amount": 6540, @@ -60,6 +68,7 @@ ] } }, + "url": { "raw": "{{baseUrl}}/payments/:id/confirm", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json index ee354325323..bed15211eea 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_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" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json index 01fa4013653..91a932b12d9 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json index ee354325323..aa51751ae1e 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json @@ -31,7 +31,15 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "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" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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" + } + }, "billing": { "address": { "line1": "1467",
2024-02-29T07:39:24Z
## Description store customer_acceptance in the payment_methods table and some changes to setup_future_usage - setup_future_usage should be inferred from the create and if passed in confirm should override the one in create - If customer_acceptance is passed then only the card will be saved on hyper switch's end ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? -make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
5eff9d47d3e53d380ef792a8fbdf06ecf78d3d16
-make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }}, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
[ "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/data_models/src/mandates.rs", "crates/router/src/core/mandate.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/flows/authorize_flow.rs", "crate...
juspay/hyperswitch
juspay__hyperswitch-3878
Bug: [FEATURE] : [Noon] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index fff99109b28..fdcb2ad5afc 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -1,6 +1,6 @@ use common_utils::{ext_traits::Encode, pii}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -124,7 +124,7 @@ pub struct NoonConfiguration { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonSubscription { - subscription_identifier: String, + subscription_identifier: Secret<String>, } #[derive(Debug, Serialize)] @@ -230,9 +230,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let (payment_data, currency, category) = match item.request.connector_mandate_id() { - Some(subscription_identifier) => ( + Some(mandate_id) => ( NoonPaymentData::Subscription(NoonSubscription { - subscription_identifier, + subscription_identifier: Secret::new(mandate_id), }), None, None, @@ -512,7 +512,7 @@ impl ForeignFrom<(NoonPaymentStatus, Self)> for enums::AttemptStatus { #[derive(Debug, Serialize, Deserialize)] pub struct NoonSubscriptionObject { - identifier: String, + identifier: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -566,7 +566,7 @@ impl<F, T> .result .subscription .map(|subscription_data| types::MandateReference { - connector_mandate_id: Some(subscription_data.identifier), + connector_mandate_id: Some(subscription_data.identifier.expose()), payment_method_id: None, }); Ok(Self { @@ -678,7 +678,7 @@ impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest { Ok(Self { api_operation: NoonApiOperations::CancelSubscription, subscription: NoonSubscriptionObject { - identifier: item.request.get_connector_mandate_id()?, + identifier: Secret::new(item.request.get_connector_mandate_id()?), }, }) }
2024-02-28T13:57:26Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Noon. ## Test Case 1. Create a mandate payment with Noon ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DSA7zgwLkTw5bHT6khsixyQNDlvsM6HDvyhxwMulGlRk8gnjJwejcmvOCniHFWT6' \ --data-raw '{ "amount": 10000, "currency": "AED", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "c1", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AE", "first_name": "John", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AE", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "13.232.74.226" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "pru": "value1" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4000000000002503", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "Joseph Doe", "card_cvc": "124" } }, "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } } , "mandate_type": { "multi_use": { "amount": 700, "currency": "AED" } } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` 2. Create a MIT ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{}}' \ --data '{ "amount": 700, "currency": "AED", "off_session": true, "confirm": true, "capture_method": "automatic", "description": "Initiated by merchant", "mandate_id": "man_spNAzYmZ2Sq3119WEe4q", "customer_id": "c1", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } } }' ``` 3. Check if `subscription_data.identifier` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` "masked_response\":\"{\\\"result\\\":{\\\"order\\\":{\\\"status\\\":\\\"CAPTURED\\\",\\\"id\\\":510639573125,\\\"errorCode\\\":0,\\\"errorMessage\\\":null,\\\"reference\\\":\\\"pay_7WNBRRI9bCY29pnKwDn8_1\\\"},\\\"checkoutData\\\":null,\\\"subscription\\\":{\\\"identifier\\\":\\\"*** alloc::string::String ***\\\"}} ``` ``` "masked_response\":\"{\\\"result\\\":{\\\"order\\\":{\\\"status\\\":\\\"CAPTURED\\\",\\\"id\\\":291984139449,\\\"errorCode\\\":0,\\\"errorMessage\\\":null,\\\"reference\\\":\\\"pay_LqEgkjiIOHZfT7ax1QHl_1\\\"},\\\"checkoutData\\\":null,\\\"subscription\\\":{\\\"identifier\\\":\\\"*** alloc::string::String ***\\\"}}} ```
032d58cdbbf388cf25cbf2e43b0117b83f7d076d
[ "crates/router/src/connector/noon/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3875
Bug: [FEATURE] : [NMI] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 2f8505522b2..efde37d8715 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -258,7 +258,7 @@ pub struct NmiCompleteRequest { transaction_type: TransactionType, security_key: Secret<String>, orderid: Option<String>, - customer_vault_id: String, + customer_vault_id: Secret<String>, email: Option<Email>, cardholder_auth: Option<String>, cavv: Option<String>, @@ -266,8 +266,9 @@ pub struct NmiCompleteRequest { eci: Option<String>, cvv: Secret<String>, three_ds_version: Option<String>, - directory_server_id: Option<String>, + directory_server_id: Option<Secret<String>>, } + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] @@ -292,8 +293,8 @@ pub struct NmiRedirectResponseData { card_holder_auth: Option<String>, three_ds_version: Option<String>, order_id: Option<String>, - directory_server_id: Option<String>, - customer_vault_id: String, + directory_server_id: Option<Secret<String>>, + customer_vault_id: Secret<String>, } impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest {
2024-02-28T13:27:17Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for NMI. ## Test Case 1. Create a NMI 3ds payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_IjTXpFN88jjlzCgq9fDoJQkxPlxCFLrX2YcbkN1XMD29aEuzJK8ew3rtsEfC1Fp6' \ --data-raw '{ "amount": 6540, "currency": "PLN", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 6540, "capture_method": "automatic", "customer_id": "AKS1", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://hs-payments-test.netlify.app/payments", "email": "arjun.karthik@juspay.in", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "838" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "Harrison Street", "city": "San Fransico", "state": "New York", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "amount": 3200, "account_name": "transaction_processing" } } }' ``` 2. Check if `apple_pay_payment_token` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` request\":\"{\\\"security_key\\\":\\\"*** alloc::string::String ***\\\",\\\"ccnumber\\\":\\\"411111**********\\\",\\\"ccexp\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\",\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"address2\\\":\\\"*** alloc::string::String ***\\\",\\\"city\\\":\\\"San Fransico\\\",\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"zip\\\":\\\"*** alloc::string::String ***\\\",\\\"country\\\":\\\"US\\\",\\\"customer_vault\\\":\\\"add_customer\\\"}\", "masked_response\":\"{\\\"response\\\":\\\"Approved\\\",\\\"responsetext\\\":\\\"Customer Added\\\",\\\"customer_vault_id\\\":\\\"*** alloc::string::String ***\\\",\\\"response_code\\\":\\\"100\\\",\\\"transactionid\\\":\\\"\\\"} ```
44eef46e5d7f0a198be80602ceae1c843449319c
[ "crates/router/src/connector/nmi/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3873
Bug: FEATURE] : [Nexinets] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 07488271aea..9fdaaa36b36 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -3,7 +3,7 @@ use base64::Engine; use cards::CardNumber; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; @@ -86,7 +86,7 @@ pub struct CardDetails { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentInstrument { - payment_instrument_id: Option<String>, + payment_instrument_id: Option<Secret<String>>, } #[derive(Debug, Serialize)] @@ -357,7 +357,7 @@ impl<F, T> .payment_instrument .payment_instrument_id .map(|id| types::MandateReference { - connector_mandate_id: Some(id), + connector_mandate_id: Some(id.expose()), payment_method_id: None, }); Ok(Self { @@ -641,7 +641,7 @@ fn get_card_data( true => { let card_data = match item.request.off_session { Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument { - payment_instrument_id: item.request.connector_mandate_id(), + payment_instrument_id: item.request.connector_mandate_id().map(Secret::new), })), _ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)), };
2024-02-28T12:17:11Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Nexinets. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a mandate payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+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": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 799, "currency": "USD" } } } }' ``` 1.b. Check if all the sensitive data in the `masked_response` and also in `request` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response: ``` masked_response\ : {\\\"orderId\\\":\\\"qyompda9ts\\\",\\\"transactionType\\\":\\\"DEBIT\\\",\\\"transactions\\\":[{\\\"transactionId\\\":\\\"transaction_bsglkkgnm3\\\",\\\"type\\\":\\\"DEBIT\\\",\\\"currency\\\":\\\"EUR\\\",\\\"status\\\":\\\"PENDING\\\"}],\\\"paymentInstrument\\\":{\\\"paymentInstrumentId\\\":\\\"*** alloc::string::String ***\\\"} ``` _Note:MIT is not fully implemented in Nexinets_ ## Impact Area 1. CIT Payment create
d220e815dc81925b205fb57d5d4f05883c1a7cde
[ "crates/router/src/connector/nexinets/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3871
Bug: feat: add groups for get_role_from_token api
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index f46c5cf312b..aee2b3fb66c 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,8 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ - CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, - RoleInfoWithPermissionsResponse, UpdateRoleRequest, + CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse, + RoleInfoResponse, RoleInfoWithPermissionsResponse, UpdateRoleRequest, }, AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest, @@ -20,5 +20,6 @@ common_utils::impl_misc_api_event_type!( CreateRoleRequest, UpdateRoleRequest, ListRolesResponse, - RoleInfoResponse + RoleInfoResponse, + GetRoleFromTokenResponse ); diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index fafb8fede0b..6d0bb2154d9 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -23,6 +23,13 @@ pub struct GetGroupsQueryParam { pub groups: Option<bool>, } +#[derive(Debug, serde::Serialize)] +#[serde(untagged)] +pub enum GetRoleFromTokenResponse { + Permissions(Vec<Permission>), + Groups(Vec<PermissionGroup>), +} + #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum RoleInfoResponse { diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index cc31798bd8b..c3d534f8860 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -1,7 +1,4 @@ -use api_models::user_role::{ - role::{self as role_api}, - Permission, -}; +use api_models::user_role::role::{self as role_api}; use common_enums::RoleScope; use common_utils::generate_id_with_default_len; use diesel_models::role::{RoleNew, RoleUpdate}; @@ -20,10 +17,10 @@ use crate::{ utils, }; -pub async fn get_role_from_token( +pub async fn get_role_from_token_with_permissions( state: AppState, user_from_token: UserFromToken, -) -> UserResponse<Vec<Permission>> { +) -> UserResponse<role_api::GetRoleFromTokenResponse> { let role_info = user_from_token .get_role_info_from_db(&state) .await @@ -35,7 +32,25 @@ pub async fn get_role_from_token( .map(Into::into) .collect(); - Ok(ApplicationResponse::Json(permissions)) + Ok(ApplicationResponse::Json( + role_api::GetRoleFromTokenResponse::Permissions(permissions), + )) +} + +pub async fn get_role_from_token_with_groups( + state: AppState, + user_from_token: UserFromToken, +) -> UserResponse<role_api::GetRoleFromTokenResponse> { + let role_info = user_from_token + .get_role_info_from_db(&state) + .await + .attach_printable("Invalid role_id in JWT")?; + + let permissions = role_info.get_permission_groups().to_vec(); + + Ok(ApplicationResponse::Json( + role_api::GetRoleFromTokenResponse::Groups(permissions), + )) } pub async fn create_role( diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 75de9e7e6f7..65e2aa4cdb8 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -41,14 +41,27 @@ pub async fn get_authorization_info( .await } -pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn get_role_from_token( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<role_api::GetGroupsQueryParam>, +) -> HttpResponse { let flow = Flow::GetRoleFromToken; + let respond_with_groups = query.into_inner().groups.unwrap_or(false); + Box::pin(api::server_wrap( flow, state.clone(), &req, (), - |state, user, _| role_core::get_role_from_token(state, user), + |state, user, _| async move { + // TODO: Permissions to be deprecated once groups are stable + if respond_with_groups { + role_core::get_role_from_token_with_groups(state, user).await + } else { + role_core::get_role_from_token_with_permissions(state, user).await + } + }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, ))
2024-02-28T12:10:44Z
## Description <!-- Describe your changes in detail --> Get role from token will respond with groups if asked. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3871 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The following api will take a query param called `groups` and if it is set to `true` it will respond with array of groups. This api was already present previously but was responding with permissions. The default behaviour without the `groups` query param is still the same (permissions will be returned). Groups will only be returned when `groups` param is set to true. ``` curl --location 'http://localhost:8080/user/role?groups=true' \ --header 'Authorization: Bearer JWT' ``` ``` [ "users_view" ] ```
f3931cf484f61a4d9c107c362d0f3f6ee872e0e7
The following api will take a query param called `groups` and if it is set to `true` it will respond with array of groups. This api was already present previously but was responding with permissions. The default behaviour without the `groups` query param is still the same (permissions will be returned). Groups will only be returned when `groups` param is set to true. ``` curl --location 'http://localhost:8080/user/role?groups=true' \ --header 'Authorization: Bearer JWT' ``` ``` [ "users_view" ] ```
[ "crates/api_models/src/events/user_role.rs", "crates/api_models/src/user_role/role.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/routes/user_role.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3868
Bug: [FEATURE] : [Multisafepay] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index bb81717fd67..a96a87f05c8 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -27,6 +27,7 @@ pub trait SerializableSecret: Serialize {} impl SerializableSecret for Value {} impl SerializableSecret for u8 {} impl SerializableSecret for u16 {} +impl SerializableSecret for i32 {} impl<'de, T, I> Deserialize<'de> for Secret<T, I> where diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 86096ed508b..f6051ea05de 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -1,4 +1,4 @@ -use common_utils::pii::Email; +use common_utils::pii::{Email, IpAddress}; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use url::Url; @@ -68,7 +68,7 @@ pub enum Gateway { #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Coupons { - pub allow: Option<Vec<String>>, + pub allow: Option<Vec<Secret<String>>>, } #[serde_with::skip_serializing_none] @@ -126,20 +126,20 @@ pub struct Browser { pub struct Customer { pub browser: Option<Browser>, pub locale: Option<String>, - pub ip_address: Option<String>, - pub forward_ip: Option<String>, - pub first_name: Option<String>, - pub last_name: Option<String>, - pub gender: Option<String>, - pub birthday: Option<String>, - pub address1: Option<String>, - pub address2: Option<String>, - pub house_number: Option<String>, - pub zip_code: Option<String>, + pub ip_address: Option<Secret<String, IpAddress>>, + pub forward_ip: Option<Secret<String, IpAddress>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, + pub gender: Option<Secret<String>>, + pub birthday: Option<Secret<String>>, + pub address1: Option<Secret<String>>, + pub address2: Option<Secret<String>>, + pub house_number: Option<Secret<String>>, + pub zip_code: Option<Secret<String>>, pub city: Option<String>, pub state: Option<String>, pub country: Option<String>, - pub phone: Option<String>, + pub phone: Option<Secret<String>>, pub email: Option<Email>, pub user_agent: Option<String>, pub referrer: Option<String>, @@ -150,7 +150,7 @@ pub struct Customer { pub struct CardInfo { pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, - pub card_expiry_date: Option<i32>, + pub card_expiry_date: Option<Secret<i32>>, pub card_cvc: Option<Secret<String>>, pub flexible_3d: Option<bool>, pub moto: Option<bool>, @@ -159,7 +159,7 @@ pub struct CardInfo { #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct GpayInfo { - pub payment_token: Option<String>, + pub payment_token: Option<Secret<String>>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -242,7 +242,7 @@ pub struct MultisafepayPaymentsRequest { pub shopping_cart: Option<ShoppingCart>, pub items: Option<String>, pub recurring_model: Option<MandateType>, - pub recurring_id: Option<String>, + pub recurring_id: Option<Secret<String>>, pub capture: Option<String>, pub days_active: Option<i32>, pub seconds_active: Option<i32>, @@ -423,7 +423,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> let gateway_info = match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo { card_number: Some(ccard.card_number.clone()), - card_expiry_date: Some( + card_expiry_date: Some(Secret::new( (format!( "{}{}", ccard.get_card_expiry_year_2_digit()?.expose(), @@ -431,7 +431,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> )) .parse::<i32>() .unwrap_or_default(), - ), + )), card_cvc: Some(ccard.card_cvc.clone()), card_holder_name: None, flexible_3d: None, @@ -442,7 +442,9 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> api::WalletData::GooglePay(ref google_pay) => { Some(GatewayInfo::Wallet(WalletInfo::GooglePay({ GpayInfo { - payment_token: Some(google_pay.tokenization_data.token.clone()), + payment_token: Some(Secret::new( + google_pay.tokenization_data.token.clone(), + )), } }))) } @@ -543,7 +545,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> .and_then(|mandate_ids| match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_ids, - )) => connector_mandate_ids.connector_mandate_id, + )) => connector_mandate_ids.connector_mandate_id.map(Secret::new), _ => None, }), days_active: Some(30), @@ -619,13 +621,13 @@ pub struct Data { #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub struct MultisafepayPaymentDetails { - pub account_holder_name: Option<String>, - pub account_id: Option<String>, - pub card_expiry_date: Option<i32>, + pub account_holder_name: Option<Secret<String>>, + pub account_id: Option<Secret<String>>, + pub card_expiry_date: Option<Secret<String>>, pub external_transaction_id: Option<serde_json::Value>, - pub last4: Option<serde_json::Value>, + pub last4: Option<Secret<String>>, pub recurring_flow: Option<String>, - pub recurring_id: Option<String>, + pub recurring_id: Option<Secret<String>>, pub recurring_model: Option<String>, #[serde(rename = "type")] pub payment_type: Option<String>, @@ -685,7 +687,7 @@ impl<F, T> .payment_details .and_then(|payment_details| payment_details.recurring_id) .map(|id| types::MandateReference { - connector_mandate_id: Some(id), + connector_mandate_id: Some(id.expose()), payment_method_id: None, }), connector_metadata: None,
2024-02-28T11:15:44Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Mulisafepay. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 2. Check if `apple_pay_payment_token` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response ``` request \":\"{\\\"type\\\":\\\"direct\\\",\\\"gateway\\\":\\\"VISA\\\",\\\"order_id\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\",\\\"currency\\\":\\\"USD\\\",\\\"amount\\\":6540,\\\"description\\\":\\\"Its my first payment request\\\",\\\"payment_options\\\":{\\\"redirect_url\\\":\\\"http://localhost:8080/payments/pay_aqRMznVMpndvmmh3IweN/merchant_1709116328/redirect/response/multisafepay\\\",\\\"cancel_url\\\":\\\"http://localhost:8080/payments/pay_aqRMznVMpndvmmh3IweN/merchant_1709116328/redirect/response/multisafepay\\\"},\\\"customer\\\":{\\\"email\\\":\\\"*********@gmail.com\\\",\\\"reference\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\"},\\\"gateway_info\\\":{\\\"card_number\\\":\\\"411111**********\\\",\\\"card_holder_name\\\":null,\\\"card_expiry_date\\\":\\\"*** i32 ***\\\",\\\"card_cvc\\\":\\\"*** alloc::string::String ***\\\",\\\"flexible_3d\\\":null,\\\"moto\\\":null,\\\"term_url\\\":null},\\\"delivery\\\":{\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"house_number\\\":\\\"*** alloc::string::String ***\\\",\\\"zip_code\\\":\\\"*** alloc::string::String ***\\\",\\\"city\\\":\\\"San Fransico\\\",\\\"country\\\":\\\"US\\\"},\\\"days_active\\\":30,\\\"seconds_active\\\":259200}\", "masked_response\":\"{\\\"success\\\":true,\\\"data\\\":{\\\"type\\\":null,\\\"order_id\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\",\\\"currency\\\":\\\"USD\\\",\\\"amount\\\":6540,\\\"description\\\":\\\"Its my first payment request\\\",\\\"capture\\\":null,\\\"payment_url\\\":\\\"https://testpay.multisafepay.com/customer-verification?sessionid=823HdSBIRUOQocDMYVsEILa3mj9hkmSKeRQ&type=3ds&md=2db93e2cd11234567890%2C0e728044058c4081898bbd2db93e2cd1&lang=en_US\\\",\\\"status\\\":\\\"initialized\\\",\\\"error_code\\\":null,\\\"error_info\\\":null,\\\"payment_details\\\":{\\\"account_holder_name\\\":null,\\\"account_id\\\":null,\\\"card_expiry_date\\\":\\\"*** alloc::string::String ***\\\",\\\"external_transaction_id\\\":null,\\\"last4\\\":\\\"*** alloc::string::String ***\\\",\\\"recurring_flow\\\":null,\\\"recurring_id\\\":null,\\\"recurring_model\\\":null,\\\"type\\\":\\\"VISA\\\"}}}\",\"error\":null,\"url\":\"https://testapi.multisafepay.com/v1/json/orders?api_key=86c095c1595b4b5cdc4462ec9b6c35ec9302a37e\",\"method\":\"POST\",\"payment_id\":\"pay_aqRMznVMpndvmmh3IweN\",\"merchant_id\":\"merchant_1709116328\",\"created_at\":1709118709865,\"request_id\":\"018def69-d6e4-7db8-b4af-f3f9b786fc84\",\"latency\":2345,\"refund_id\":null,\"dispute_id\":null,\"status_code\":200} ```
53559c22527dde9536aa493ad7cd3bf353335c1a
[ "crates/masking/src/serde.rs", "crates/router/src/connector/multisafepay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3864
Bug: feat: Add Cookie in response header Using cookies for storing login token instead of local storage. Add `set-cookie` response header with json-web-token as its value.
diff --git a/Cargo.lock b/Cargo.lock index 2e4d3324d2e..7c7b2b9a761 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -224,7 +224,7 @@ dependencies = [ "bytes 1.5.0", "bytestring", "cfg-if 1.0.0", - "cookie", + "cookie 0.16.2", "derive_more", "encoding_rs", "futures-core", @@ -616,7 +616,7 @@ dependencies = [ "base64 0.21.5", "bytes 1.5.0", "cfg-if 1.0.0", - "cookie", + "cookie 0.16.2", "derive_more", "futures-core", "futures-util", @@ -1763,6 +1763,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cd91cf61412820176e137621345ee43b3f4423e589e7ae4e50d601d93e35ef8" +dependencies = [ + "time", + "version_check", +] + [[package]] name = "cookie-factory" version = "0.3.2" @@ -2524,7 +2534,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65f0fbe245d714b596ba5802b46f937f5ce68dcae0f32f9a70b5c3b04d3c6f64" dependencies = [ "base64 0.13.1", - "cookie", + "cookie 0.16.2", "futures-core", "futures-util", "http", @@ -5219,6 +5229,7 @@ dependencies = [ "common_enums", "common_utils", "config", + "cookie 0.18.0", "currency_conversion", "data_models", "derive_deref", @@ -6414,7 +6425,7 @@ dependencies = [ "async-trait", "base64 0.13.1", "chrono", - "cookie", + "cookie 0.16.2", "fantoccini", "futures 0.3.28", "http", @@ -7461,7 +7472,7 @@ checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f" dependencies = [ "base64 0.13.1", "bytes 1.5.0", - "cookie", + "cookie 0.16.2", "http", "log", "serde", diff --git a/crates/masking/src/maskable.rs b/crates/masking/src/maskable.rs index 3469e1dd746..7969c9ab8e4 100644 --- a/crates/masking/src/maskable.rs +++ b/crates/masking/src/maskable.rs @@ -58,6 +58,24 @@ impl<T: Eq + PartialEq + Clone> Maskable<T> { pub fn new_normal(item: T) -> Self { Self::Normal(item) } + + /// + /// Checks whether the data is masked. + /// Returns `true` if the data is wrapped in the `Masked` variant, + /// returns `false` otherwise. + /// + pub fn is_masked(&self) -> bool { + matches!(self, Self::Masked(_)) + } + + /// + /// Checks whether the data is normal (not masked). + /// Returns `true` if the data is wrapped in the `Normal` variant, + /// returns `false` otherwise. + /// + pub fn is_normal(&self) -> bool { + matches!(self, Self::Normal(_)) + } } /// Trait for providing a method on custom types for constructing `Maskable` diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 9cb7913211f..f001609ee88 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -46,6 +46,7 @@ blake3 = "1.3.3" bytes = "1.4.0" clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } +cookie = "0.18.0" diesel = { version = "2.1.0", features = ["postgres"] } digest = "0.9" dyn-clone = "1.0.11" diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 26598493c87..70add106762 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -68,6 +68,8 @@ pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days +pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token"; + pub const USER_BLACKLIST_PREFIX: &str = "BU_"; pub const ROLE_BLACKLIST_PREFIX: &str = "BR_"; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 3cb11d1c0e9..9dd7df66fa6 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -5,6 +5,7 @@ use common_enums::RequestIncrementalAuthorization; use common_utils::{consts::X_HS_LATENCY, fp_utils}; use diesel_models::ephemeral_key; use error_stack::{report, IntoReport, ResultExt}; +use masking::Maskable; use router_env::{instrument, tracing}; use super::{flows::Feature, PaymentData}; @@ -466,20 +467,25 @@ where .map(|status_code| { vec![( "connector_http_status_code".to_string(), - status_code.to_string(), + Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); if let Some(payment_confirm_source) = payment_intent.payment_confirm_source { headers.push(( "payment_confirm_source".to_string(), - payment_confirm_source.to_string(), + Maskable::new_normal(payment_confirm_source.to_string()), )) } headers.extend( external_latency - .map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())]) + .map(|latency| { + vec![( + X_HS_LATENCY.to_string(), + Maskable::new_normal(latency.to_string()), + )] + }) .unwrap_or_default(), ); diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c1e10ddfabf..703c6443160 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -93,12 +93,13 @@ pub async fn signup( UserStatus::Active, ) .await?; - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; - Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, - )) + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + let response = + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; + + auth::cookies::set_cookie_response(response, token) } pub async fn signin_without_invite_checks( @@ -121,12 +122,12 @@ pub async fn signin_without_invite_checks( user_from_db.compare_password(request.password)?; let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; - Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, - )) + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + let response = + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; + auth::cookies::set_cookie_response(response, token) } pub async fn signin( @@ -168,9 +169,9 @@ pub async fn signin( .await? }; - Ok(ApplicationResponse::Json( - signin_strategy.get_signin_response(&state).await?, - )) + let response = signin_strategy.get_signin_response(&state).await?; + let token = utils::user::get_token_from_signin_response(&response); + auth::cookies::set_cookie_response(response, token) } #[cfg(feature = "email")] @@ -271,7 +272,7 @@ pub async fn connect_account( pub async fn signout(state: AppState, user_from_token: auth::UserFromToken) -> UserResponse<()> { auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } pub async fn change_password( @@ -971,14 +972,14 @@ pub async fn accept_invite_from_email( utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result) .await; - Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response( - &state, - user_from_db, - update_status_result, - token, - )?, - )) + let response = utils::user::get_dashboard_entry_response( + &state, + user_from_db, + update_status_result, + token.clone(), + )?; + + auth::cookies::set_cookie_response(response, token) } pub async fn create_internal_user( @@ -1130,17 +1131,17 @@ pub async fn switch_merchant_id( (token, user_role.role_id.clone()) }; - Ok(ApplicationResponse::Json( - user_api::DashboardEntryResponse { - token, - 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, - }, - )) + 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( @@ -1318,9 +1319,10 @@ pub async fn verify_email_without_invite_checks( let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; - Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, - )) + let response = + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; + + auth::cookies::set_cookie_response(response, token) } #[cfg(feature = "email")] @@ -1373,9 +1375,9 @@ pub async fn verify_email( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::Json( - signin_strategy.get_signin_response(&state).await?, - )) + let response = signin_strategy.get_signin_response(&state).await?; + let token = utils::user::get_token_from_signin_response(&response); + auth::cookies::set_cookie_response(response, token) } #[cfg(feature = "email")] diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b81b980c07a..587e0e04435 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -158,12 +158,13 @@ pub async fn transfer_org_ownership( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; - Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, - )) + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + let response = + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; + + auth::cookies::set_cookie_response(response, token) } pub async fn accept_invitation( @@ -202,12 +203,17 @@ pub async fn accept_invitation( .change_context(UserErrors::InternalServerError)? .into(); - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; - return Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, - )); + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + let response = utils::user::get_dashboard_entry_response( + &state, + user_from_db, + user_role, + token.clone(), + )?; + return auth::cookies::set_cookie_response(response, token); } Ok(ApplicationResponse::StatusOk) diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index bc8e3b99d23..00558e6c4f4 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -9,7 +9,10 @@ use std::{ time::{Duration, Instant}, }; -use actix_web::{body, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError}; +use actix_web::{ + body, http::header::HeaderValue, web, FromRequest, HttpRequest, HttpResponse, Responder, + ResponseError, +}; use api_models::enums::{CaptureMethod, PaymentMethodType}; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; use common_enums::Currency; @@ -20,7 +23,7 @@ use common_utils::{ request::RequestContent, }; use error_stack::{report, IntoReport, Report, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{Maskable, PeekInterface, Secret}; use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use serde_json::json; @@ -110,7 +113,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re &self, _req: &types::RouterData<T, Req, Resp>, _connectors: &Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } @@ -847,7 +850,7 @@ pub enum ApplicationResponse<R> { Form(Box<RedirectionFormData>), PaymentLinkForm(Box<PaymentLinkAction>), FileData((Vec<u8>, mime::Mime)), - JsonWithHeaders((R, Vec<(String, String)>)), + JsonWithHeaders((R, Vec<(String, Maskable<String>)>)), } #[derive(Debug, Eq, PartialEq)] @@ -1046,7 +1049,7 @@ where ); if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) { - if let Ok(external_latency) = value.parse::<u128>() { + if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() { overhead_latency.replace(external_latency); } } @@ -1126,7 +1129,7 @@ where let incoming_request_header = request.headers(); - let incoming_header_to_log: HashMap<String, http::header::HeaderValue> = + let incoming_header_to_log: HashMap<String, HeaderValue> = incoming_request_header .iter() .fold(HashMap::new(), |mut acc, (key, value)| { @@ -1333,21 +1336,33 @@ pub fn http_server_error_json_response<T: body::MessageBody + 'static>( pub fn http_response_json_with_headers<T: body::MessageBody + 'static>( response: T, - mut headers: Vec<(String, String)>, + headers: Vec<(String, Maskable<String>)>, request_duration: Option<Duration>, ) -> HttpResponse { let mut response_builder = HttpResponse::Ok(); - - for (name, value) in headers.iter_mut() { - if name == X_HS_LATENCY { + for (header_name, header_value) in headers { + let is_sensitive_header = header_value.is_masked(); + let mut header_value = header_value.into_inner(); + if header_name == X_HS_LATENCY { if let Some(request_duration) = request_duration { - if let Ok(external_latency) = value.parse::<u128>() { + if let Ok(external_latency) = header_value.parse::<u128>() { let updated_duration = request_duration.as_millis() - external_latency; - *value = updated_duration.to_string(); + header_value = updated_duration.to_string(); } } } - response_builder.append_header((name.clone(), value.clone())); + let mut header_value = match HeaderValue::from_str(header_value.as_str()) { + Ok(header_value) => header_value, + Err(e) => { + logger::error!(?e); + return http_server_error_json_response("Something Went Wrong"); + } + }; + + if is_sensitive_header { + header_value.set_sensitive(true); + } + response_builder.append_header((header_name, header_value)); } response_builder diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7cf1855b441..eb115f5701c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -33,6 +33,8 @@ use crate::{ utils::OptionExt, }; pub mod blacklist; +#[cfg(feature = "olap")] +pub mod cookies; #[derive(Clone, Debug)] pub struct AuthenticationData { diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs new file mode 100644 index 00000000000..d7fc4c10315 --- /dev/null +++ b/crates/router/src/services/authentication/cookies.rs @@ -0,0 +1,62 @@ +use cookie::{ + time::{Duration, OffsetDateTime}, + Cookie, SameSite, +}; +use masking::{ExposeInterface, Mask, Secret}; + +use crate::{ + consts::{JWT_TOKEN_COOKIE_NAME, JWT_TOKEN_TIME_IN_SECS}, + core::errors::{UserErrors, UserResponse}, + services::ApplicationResponse, +}; + +pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> { + let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS + .try_into() + .map_err(|_| UserErrors::InternalServerError)?; + let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds); + + let header_value = create_cookie(token, expiry, max_age) + .to_string() + .into_masked(); + let header_key = get_cookie_header(); + let header = vec![(header_key, header_value)]; + + Ok(ApplicationResponse::JsonWithHeaders((response, header))) +} + +pub fn remove_cookie_response() -> UserResponse<()> { + let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0); + + let header_key = get_cookie_header(); + let header_value = create_cookie("".to_string().into(), expiry, max_age) + .to_string() + .into_masked(); + let header = vec![(header_key, header_value)]; + Ok(ApplicationResponse::JsonWithHeaders(((), header))) +} + +fn create_cookie<'c>( + token: Secret<String>, + expires: OffsetDateTime, + max_age: Duration, +) -> Cookie<'c> { + Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose())) + .http_only(true) + .secure(true) + .same_site(SameSite::Strict) + .path("/") + .expires(expires) + .max_age(max_age) + .build() +} + +fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) { + let max_age = Duration::seconds(seconds); + let expiry = OffsetDateTime::now_utc().saturating_add(max_age); + (expiry, max_age) +} + +fn get_cookie_header() -> String { + actix_http::header::SET_COOKIE.to_string() +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index cfab331f148..e97d5ae1efd 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -170,3 +170,10 @@ pub async fn get_user_from_db_by_email( .await .map(UserFromStorage::from) } + +pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> { + match resp { + user_api::SignInResponse::DashboardEntry(data) => data.token.clone(), + user_api::SignInResponse::MerchantSelect(data) => data.token.clone(), + } +}
2024-02-28T09:45:16Z
## Description This is the first PR for cookie implementation. In this pr, `set-cookie` header has been added to response header, where value of the header is jwt. <!-- Describe your changes in detail --> ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Storing JWT in cookies instead of local storage <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Following apis should have `set-cookie` header with jwt as value. ``` curl --location '<URL>/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/verify_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/v2/verify_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/accept_invite_from_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/switch_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data '{ "merchant_id": "merchant_1707460394" }' ``` ``` curl --location '<URL>/user/user/transfer_ownership' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data-raw '{ "email": "email" }' ``` ``` curl --location '<URL>/user/user/invite/accept' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data '{ "merchant_ids": [ "merchant_1705922092", "merchant_1705414514" ], "need_dashboard_entry_response": true }' ``` Following api should have `set-cookie` header with `""` (empty value) as value. ``` curl --location '<URL>/user/signout' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data-raw '{ "email": "email" }' ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
e1b894770f3d37c2a255d3cec1d58ec71ba29c78
Following apis should have `set-cookie` header with jwt as value. ``` curl --location '<URL>/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` curl --location '<URL>/user/verify_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/v2/verify_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/accept_invite_from_email' \ --header 'Content-Type: application/json' \ --data '{ "token": "email token" }' ``` ``` curl --location '<URL>/user/switch_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data '{ "merchant_id": "merchant_1707460394" }' ``` ``` curl --location '<URL>/user/user/transfer_ownership' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data-raw '{ "email": "email" }' ``` ``` curl --location '<URL>/user/user/invite/accept' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data '{ "merchant_ids": [ "merchant_1705922092", "merchant_1705414514" ], "need_dashboard_entry_response": true }' ``` Following api should have `set-cookie` header with `""` (empty value) as value. ``` curl --location '<URL>/user/signout' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <JWT>' \ --data-raw '{ "email": "email" }' ```
[ "Cargo.lock", "crates/masking/src/maskable.rs", "crates/router/Cargo.toml", "crates/router/src/consts.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/services/api.rs", "crates/router/src/services/auth...
juspay/hyperswitch
juspay__hyperswitch-3753
Bug: Remove validation for `mandate_data` object in payments create request - Mandate data to be an optional field and not a required param for setup_future_usage:off-session payments
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 2eaa11f44ee..f4db64dcfb5 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -8,7 +8,7 @@ use data_models::{ payments::payment_attempt::PaymentAttempt, }; use diesel_models::ephemeral_key; -use error_stack::{self, report, ResultExt}; +use error_stack::{self, ResultExt}; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -628,17 +628,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 071d919eb19..494db2b8529 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -683,17 +683,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == storage_enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, false)?; Ok((
2024-02-28T08:00:08Z
## Description <!-- Describe your changes in detail --> This PR removes the validation such that mandate data to be an optional field and not a required param for setup_future_usage: off-session payments ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Before removing validation - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4df97e1a-5174-4a2e-b842-301c6494eb9c) After removing validation (same curl req)- ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Payment succeeded - ![image](https://github.com/juspay/hyperswitch/assets/70657455/7827566e-2a15-4ded-be76-c3e8e7b34079)
0fa43612c2e6c11d555efecd49e6982403a45000
Before removing validation - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4df97e1a-5174-4a2e-b842-301c6494eb9c) After removing validation (same curl req)- ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Payment succeeded - ![image](https://github.com/juspay/hyperswitch/assets/70657455/7827566e-2a15-4ded-be76-c3e8e7b34079)
[ "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/core/payments/operations/payment_update.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3855
Bug: [FEATURE] : [Mollie] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index af1159cd2c3..be4691341b8 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -64,7 +64,7 @@ pub struct MolliePaymentsRequest { payment_method_data: PaymentMethodData, metadata: Option<MollieMetadata>, sequence_type: SequenceType, - mandate_id: Option<String>, + mandate_id: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -92,7 +92,7 @@ pub enum PaymentMethodData { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayMethodData { - apple_pay_payment_token: String, + apple_pay_payment_token: Secret<String>, } #[derive(Debug, Serialize)] @@ -333,7 +333,7 @@ fn get_payment_method_for_wallet( } api_models::payments::WalletData::ApplePay(applepay_wallet_data) => { Ok(PaymentMethodData::Applepay(Box::new(ApplePayMethodData { - apple_pay_payment_token: applepay_wallet_data.payment_data.to_owned(), + apple_pay_payment_token: Secret::new(applepay_wallet_data.payment_data.to_owned()), }))) } _ => Err(errors::ConnectorError::NotImplemented( @@ -451,16 +451,16 @@ pub struct Links { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardDetails { - pub card_number: String, - pub card_holder: String, - pub card_expiry_date: String, - pub card_cvv: String, + pub card_number: Secret<String>, + pub card_holder: Secret<String>, + pub card_expiry_date: Secret<String>, + pub card_cvv: Secret<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BankDetails { - billing_email: String, + billing_email: Email, } pub struct MollieAuthType {
2024-02-27T13:26:38Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Mollie. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create an Apple pay payment 2. Check if `apple_pay_payment_token` in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ```
fbe9d2f19e9c0ca3af45a60e3d82b3ea774e11ce
[ "crates/router/src/connector/mollie/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3853
Bug: [FEATURE] : [Klarna] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index c12f8ed1b10..29dccfbf32b 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -1,6 +1,6 @@ use api_models::payments; use error_stack::report; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -66,8 +66,8 @@ pub struct KlarnaSessionRequest { #[derive(Deserialize, Serialize, Debug)] pub struct KlarnaSessionResponse { - pub client_token: String, - pub session_id: String, + pub client_token: Secret<String>, + pub session_id: Secret<String>, } impl TryFrom<&types::PaymentsSessionRouterData> for KlarnaSessionRequest { @@ -110,8 +110,8 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>> response: Ok(types::PaymentsResponseData::SessionResponse { session_token: types::api::SessionToken::Klarna(Box::new( payments::KlarnaSessionTokenResponse { - session_token: response.client_token.clone(), - session_id: response.session_id.clone(), + session_token: response.client_token.clone().expose(), + session_id: response.session_id.clone().expose(), }, )), }),
2024-02-27T13:00:03Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Klarna. ## Test Cases <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a Klarna payment with Klarna connector. Set payment experience as invoke SDK. _Note: As it requires invoking SDK, can't be tested from local_
3e13fb908adf84974312c4785cb4ce57e46a496f
[ "crates/router/src/connector/klarna/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3848
Bug: [FEATURE] : [Iatapay] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 55778af882b..b2507661395 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -261,7 +261,7 @@ pub struct IatapayPaymentsResponse { pub status: IatapayPaymentStatus, pub iata_payment_id: Option<String>, pub iata_refund_id: Option<String>, - pub merchant_id: Option<String>, + pub merchant_id: Option<Secret<String>>, pub merchant_payment_id: Option<String>, pub amount: f64, pub currency: String, @@ -428,7 +428,7 @@ pub struct RefundResponse { iata_payment_id: Option<String>, merchant_payment_id: Option<String>, payment_amount: Option<f64>, - merchant_id: Option<String>, + merchant_id: Option<Secret<String>>, account_country: Option<String>, }
2024-02-27T12:08:02Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Iatapay. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. UPI Payment Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "vpa_id": "successtest@iata" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Expected Response ``` \"masked_response\":\"{\\\"status\\\":\\\"CREATED\\\",\\\"iataPaymentId\\\":\\\"PH3WO013A5QTQ\\\",\\\"iataRefundId\\\":null,\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantPaymentId\\\":\\\"pay_JBrbR1SRhIJ1BivCvB60_1\\\",\\\"amount\\\":50.0,\\\"currency\\\":\\\"INR\\\",\\\"checkoutMethods\\\":{\\\"redirect\\\":{\\\"redirectUrl\\\":\\\"https://sandbox.iata-pay.iata.org/api/v1/payments/PH3WO013A5QTQ/checkout/redirect\\\"}},\\\"failureCode\\\":null,\\\"failureDetails\\\":null} ```
0626ca968576709a3559243f5a64e742201dbf91
[ "crates/router/src/connector/iatapay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3846
Bug: [BUG] [AUTHORIZEDOTNET] Wrong Status Mapping ### Bug Description The status mapping for connector Authorizdotnet does not mark the payment charged until it is settled. ### Expected Behavior The status mapping for connector Authorizdotnet should mark the payment charged when it is approved even though it is not settled. ### Actual Behavior The status mapping for connector Authorizdotnet does not mark the payment charged until it is settled. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index ba232c01bbf..0aba48fa5e5 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -9,7 +9,10 @@ use transformers as authorizedotnet; use crate::{ configs::settings, - connector::utils as connector_utils, + connector::{ + utils as connector_utils, + utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData}, + }, consts, core::{ errors::{self, CustomResult}, @@ -216,11 +219,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + true, + )) } fn get_error_response( @@ -405,11 +411,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + data.request.is_auto_capture()?, + )) } fn get_error_response( @@ -783,11 +792,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + data.request.is_auto_capture()?, + )) } fn get_error_response( diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index eb5f13881fb..e2718d1ac91 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -10,7 +10,7 @@ use crate::{ connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData}, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, transformers::ForeignFrom}, utils::OptionExt, }; @@ -258,8 +258,8 @@ struct TransactionVoidOrCaptureRequest { #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsRequest { merchant_authentication: AuthorizedotnetAuthType, + ref_id: Option<String>, transaction_request: TransactionRequest, - ref_id: String, } #[derive(Debug, Serialize)] @@ -326,12 +326,16 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; - + let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { + Some(item.router_data.connector_request_reference_id.clone()) + } else { + None + }; Ok(Self { create_transaction_request: AuthorizedotnetPaymentsRequest { merchant_authentication, + ref_id, transaction_request, - ref_id: item.router_data.connector_request_reference_id.clone(), }, }) } @@ -413,10 +417,16 @@ pub enum AuthorizedotnetRefundStatus { HeldForReview, } -impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { - fn from(item: AuthorizedotnetPaymentStatus) -> Self { +impl ForeignFrom<(AuthorizedotnetPaymentStatus, bool)> for enums::AttemptStatus { + fn foreign_from((item, auto_capture): (AuthorizedotnetPaymentStatus, bool)) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => Self::Pending, + AuthorizedotnetPaymentStatus::Approved => { + if auto_capture { + Self::Charged + } else { + Self::Authorized + } + } AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { Self::Failure } @@ -536,35 +546,44 @@ pub enum AuthorizedotnetVoidStatus { impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus { fn from(item: AuthorizedotnetVoidStatus) -> Self { match item { - AuthorizedotnetVoidStatus::Approved => Self::VoidInitiated, - AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => Self::Failure, - AuthorizedotnetVoidStatus::HeldForReview => Self::Pending, + AuthorizedotnetVoidStatus::Approved => Self::Voided, + AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => { + Self::VoidFailed + } + AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated, } } } impl<F, T> - TryFrom< + TryFrom<( types::ResponseRouterData< F, AuthorizedotnetPaymentsResponse, T, types::PaymentsResponseData, >, - > for types::RouterData<F, T, types::PaymentsResponseData> + bool, + )> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - AuthorizedotnetPaymentsResponse, - T, - types::PaymentsResponseData, - >, + (item, is_auto_capture): ( + types::ResponseRouterData< + F, + AuthorizedotnetPaymentsResponse, + T, + types::PaymentsResponseData, + >, + bool, + ), ) -> Result<Self, Self::Error> { match &item.response.transaction_response { Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => { - let status = enums::AttemptStatus::from(transaction_response.response_code.clone()); + let status = enums::AttemptStatus::foreign_from(( + 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 { code: error.error_code.clone(),
2024-02-27T10:08:46Z
## Description <!-- Describe your changes in detail --> - The status mapping for connector `Authorizdotnet` is fixed. - The `ref_id` field being passed in connector contains `connector_request_reference_id`. The max number of characters allowed in ref_id is 20 and hence a check has been added to only pass ref_id if connector_request_reference_id contains `less than or equal to` 20 characters. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3846 https://github.com/juspay/hyperswitch/issues/3847 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Following flows should be tested for connector Authorizdotnet: 1. Authorization(Auto Capture): ``` { "payment_id": "abcd1", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "abcd1", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 800, "net_amount": 800, "amount_capturable": 0, "amount_received": 800, "connector": "authorizedotnet", "client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu", "created": "2024-02-27T13:19:55.615Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709039995, "expires": 1709043595, "secret": "epk_d639baf128604e01adc764d9d48437c6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300949", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300949", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:34:55.615Z", "fingerprint": null } ``` 2. Authorization(Manual Capture): ``` { "payment_id": "1ss", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "requires_capture", "amount": 1200, "net_amount": 1200, "amount_capturable": 1200, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709040040, "expires": 1709043640, "secret": "epk_a94c6c4d1e594998a168081802130610" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 3. Capture: ``` curl --location 'http://localhost:8080/payments/1ss/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 1200, "net_amount": 1200, "amount_capturable": 0, "amount_received": 1200, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 4. Void: ``` curl --location 'http://localhost:8080/payments/1s2/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1s2", "merchant_id": "merchant_1708944265", "status": "cancelled", "amount": 120, "net_amount": 120, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9", "created": "2024-02-27T13:22:23.892Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015301006", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015301006", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:37:23.892Z", "fingerprint": null } ```
0626ca968576709a3559243f5a64e742201dbf91
Following flows should be tested for connector Authorizdotnet: 1. Authorization(Auto Capture): ``` { "payment_id": "abcd1", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "abcd1", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 800, "net_amount": 800, "amount_capturable": 0, "amount_received": 800, "connector": "authorizedotnet", "client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu", "created": "2024-02-27T13:19:55.615Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709039995, "expires": 1709043595, "secret": "epk_d639baf128604e01adc764d9d48437c6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300949", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300949", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:34:55.615Z", "fingerprint": null } ``` 2. Authorization(Manual Capture): ``` { "payment_id": "1ss", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "requires_capture", "amount": 1200, "net_amount": 1200, "amount_capturable": 1200, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709040040, "expires": 1709043640, "secret": "epk_a94c6c4d1e594998a168081802130610" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 3. Capture: ``` curl --location 'http://localhost:8080/payments/1ss/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 1200, "net_amount": 1200, "amount_capturable": 0, "amount_received": 1200, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 4. Void: ``` curl --location 'http://localhost:8080/payments/1s2/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1s2", "merchant_id": "merchant_1708944265", "status": "cancelled", "amount": 120, "net_amount": 120, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9", "created": "2024-02-27T13:22:23.892Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015301006", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015301006", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:37:23.892Z", "fingerprint": null } ```
[ "crates/router/src/connector/authorizedotnet.rs", "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3847
Bug: [BUG] [AUTHORIZEDOTNET] REF_ID should only allow strings which have less than 20 charcaters ### Bug Description The ref_id field being passed in connector contains connector_request_reference_id. The max number of characters allowed in ref_id is 20 while the current implementation allows it to be more than 20 characters which results in the payment getting failed at the connector end. ### Expected Behavior REF_ID should not be passed if `connector_request_reference_id` is greater than 20 characters. ### Actual Behavior REF_ID is passed even if `connector_request_reference_id` is greater than 20 characters. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index ba232c01bbf..0aba48fa5e5 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -9,7 +9,10 @@ use transformers as authorizedotnet; use crate::{ configs::settings, - connector::utils as connector_utils, + connector::{ + utils as connector_utils, + utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData}, + }, consts, core::{ errors::{self, CustomResult}, @@ -216,11 +219,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + true, + )) } fn get_error_response( @@ -405,11 +411,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + data.request.is_auto_capture()?, + )) } fn get_error_response( @@ -783,11 +792,14 @@ 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 { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + data.request.is_auto_capture()?, + )) } fn get_error_response( diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index eb5f13881fb..e2718d1ac91 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -10,7 +10,7 @@ use crate::{ connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData}, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, transformers::ForeignFrom}, utils::OptionExt, }; @@ -258,8 +258,8 @@ struct TransactionVoidOrCaptureRequest { #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsRequest { merchant_authentication: AuthorizedotnetAuthType, + ref_id: Option<String>, transaction_request: TransactionRequest, - ref_id: String, } #[derive(Debug, Serialize)] @@ -326,12 +326,16 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; - + let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { + Some(item.router_data.connector_request_reference_id.clone()) + } else { + None + }; Ok(Self { create_transaction_request: AuthorizedotnetPaymentsRequest { merchant_authentication, + ref_id, transaction_request, - ref_id: item.router_data.connector_request_reference_id.clone(), }, }) } @@ -413,10 +417,16 @@ pub enum AuthorizedotnetRefundStatus { HeldForReview, } -impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus { - fn from(item: AuthorizedotnetPaymentStatus) -> Self { +impl ForeignFrom<(AuthorizedotnetPaymentStatus, bool)> for enums::AttemptStatus { + fn foreign_from((item, auto_capture): (AuthorizedotnetPaymentStatus, bool)) -> Self { match item { - AuthorizedotnetPaymentStatus::Approved => Self::Pending, + AuthorizedotnetPaymentStatus::Approved => { + if auto_capture { + Self::Charged + } else { + Self::Authorized + } + } AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { Self::Failure } @@ -536,35 +546,44 @@ pub enum AuthorizedotnetVoidStatus { impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus { fn from(item: AuthorizedotnetVoidStatus) -> Self { match item { - AuthorizedotnetVoidStatus::Approved => Self::VoidInitiated, - AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => Self::Failure, - AuthorizedotnetVoidStatus::HeldForReview => Self::Pending, + AuthorizedotnetVoidStatus::Approved => Self::Voided, + AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => { + Self::VoidFailed + } + AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated, } } } impl<F, T> - TryFrom< + TryFrom<( types::ResponseRouterData< F, AuthorizedotnetPaymentsResponse, T, types::PaymentsResponseData, >, - > for types::RouterData<F, T, types::PaymentsResponseData> + bool, + )> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - AuthorizedotnetPaymentsResponse, - T, - types::PaymentsResponseData, - >, + (item, is_auto_capture): ( + types::ResponseRouterData< + F, + AuthorizedotnetPaymentsResponse, + T, + types::PaymentsResponseData, + >, + bool, + ), ) -> Result<Self, Self::Error> { match &item.response.transaction_response { Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => { - let status = enums::AttemptStatus::from(transaction_response.response_code.clone()); + let status = enums::AttemptStatus::foreign_from(( + 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 { code: error.error_code.clone(),
2024-02-27T10:08:46Z
## Description <!-- Describe your changes in detail --> - The status mapping for connector `Authorizdotnet` is fixed. - The `ref_id` field being passed in connector contains `connector_request_reference_id`. The max number of characters allowed in ref_id is 20 and hence a check has been added to only pass ref_id if connector_request_reference_id contains `less than or equal to` 20 characters. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3846 https://github.com/juspay/hyperswitch/issues/3847 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Following flows should be tested for connector Authorizdotnet: 1. Authorization(Auto Capture): ``` { "payment_id": "abcd1", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "abcd1", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 800, "net_amount": 800, "amount_capturable": 0, "amount_received": 800, "connector": "authorizedotnet", "client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu", "created": "2024-02-27T13:19:55.615Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709039995, "expires": 1709043595, "secret": "epk_d639baf128604e01adc764d9d48437c6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300949", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300949", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:34:55.615Z", "fingerprint": null } ``` 2. Authorization(Manual Capture): ``` { "payment_id": "1ss", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "requires_capture", "amount": 1200, "net_amount": 1200, "amount_capturable": 1200, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709040040, "expires": 1709043640, "secret": "epk_a94c6c4d1e594998a168081802130610" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 3. Capture: ``` curl --location 'http://localhost:8080/payments/1ss/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 1200, "net_amount": 1200, "amount_capturable": 0, "amount_received": 1200, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 4. Void: ``` curl --location 'http://localhost:8080/payments/1s2/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1s2", "merchant_id": "merchant_1708944265", "status": "cancelled", "amount": 120, "net_amount": 120, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9", "created": "2024-02-27T13:22:23.892Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015301006", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015301006", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:37:23.892Z", "fingerprint": null } ```
0626ca968576709a3559243f5a64e742201dbf91
Following flows should be tested for connector Authorizdotnet: 1. Authorization(Auto Capture): ``` { "payment_id": "abcd1", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "abcd1", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 800, "net_amount": 800, "amount_capturable": 0, "amount_received": 800, "connector": "authorizedotnet", "client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu", "created": "2024-02-27T13:19:55.615Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709039995, "expires": 1709043595, "secret": "epk_d639baf128604e01adc764d9d48437c6" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300949", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300949", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:34:55.615Z", "fingerprint": null } ``` 2. Authorization(Manual Capture): ``` { "payment_id": "1ss", "amount": 800, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` NOTE: Try passing the above curl without payment_id also. Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "requires_capture", "amount": 1200, "net_amount": 1200, "amount_capturable": 1200, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1709040040, "expires": 1709043640, "secret": "epk_a94c6c4d1e594998a168081802130610" }, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 3. Capture: ``` curl --location 'http://localhost:8080/payments/1ss/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1ss", "merchant_id": "merchant_1708944265", "status": "succeeded", "amount": 1200, "net_amount": 1200, "amount_capturable": 0, "amount_received": 1200, "connector": "authorizedotnet", "client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP", "created": "2024-02-27T13:20:40.683Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015300969", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015300969", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:35:40.683Z", "fingerprint": null } ``` 4. Void: ``` curl --location 'http://localhost:8080/payments/1s2/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{}' ``` Response: ``` { "payment_id": "1s2", "merchant_id": "merchant_1708944265", "status": "cancelled", "amount": 120, "net_amount": 120, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9", "created": "2024-02-27T13:22:23.892Z", "currency": "USD", "customer_id": "StripeCustomer", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": "42424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80015301006", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80015301006", "payment_link": null, "profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-27T13:37:23.892Z", "fingerprint": null } ```
[ "crates/router/src/connector/authorizedotnet.rs", "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3843
Bug: [FEATURE] : [Gocardless] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index d3703bc6bf8..21fc44fe84f 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -547,7 +547,7 @@ pub struct GocardlessMandateResponse { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct MandateResponse { - id: String, + id: Secret<String>, } impl<F> @@ -570,7 +570,7 @@ impl<F> >, ) -> Result<Self, Self::Error> { let mandate_reference = Some(MandateReference { - connector_mandate_id: Some(item.response.mandates.id.clone()), + connector_mandate_id: Some(item.response.mandates.id.clone().expose()), payment_method_id: None, }); Ok(Self {
2024-02-27T10:00:29Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Gocardless. ## Test Case 1. Create a payment intent with Gocardless ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{}}' \ --data-raw '{ "amount": 0, "order_details": null, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "three_ds", "customer_id": "arjun", "email": "hyperswitch_sdk_demo_id@gmail.com", "description": "Hello this is description", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "metadata": {}, "setup_future_usage": "off_session", "mandate_data": { "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD" } } } }' ``` 2.Confirm the mandate payment ``` curl --location 'http://localhost:8080/payments/pay_FXMSggPlgoGMg9r6AlpY/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_BRdlOJtJTl8WPK503hzNIbM8mTJC7Ayp1D4tiMyP9JzUXTEvR1N65YLI4uy7C2w2' \ --data-raw '{ "return_url": "http://localhost:9060/completion", "payment_method": "bank_debit", "setup_future_usage": "off_session", "payment_method_type": "ach", "payment_type": "setup_mandate", "payment_method_data": { "bank_debit": { "ach_bank_debit": { "billing_details": { "name": "Shivam S", "email": "test@test.com", "address": { "line1": "123", "line2": "123", "city": "vjnsf", "state": "Alaska", "zip": "10001", "country": "US" } }, "account_number": "27155003358", "bank_account_holder_name": "tests tests", "routing_number": "026073150", "bank_type": "checking" } } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2023-12-07T12:16:08.622Z", "online": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" } }' ``` 3. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response should contain: ``` "masked_response\":\"{\\\"mandates\\\":{\\\"id\\\":\\\"*** alloc::string::String ***\\\"}} ```
cd1a17bcd260629aad7548ff274f5512c37bfab7
[ "crates/router/src/connector/gocardless/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-217
Bug: [FEATURE] Schedule webhook for retry ## Description Refactor webhooks core to add retry logic in webhooks core. Currently, we store information about whether we have sent a webhook or not, improving on this we can implement retry logic to make this more reliable
diff --git a/.typos.toml b/.typos.toml index 40acb130589..2d2e165544a 100644 --- a/.typos.toml +++ b/.typos.toml @@ -2,6 +2,7 @@ check-filename = true [default.extend-identifiers] +"ABD" = "ABD" # Aberdeenshire, UK ISO 3166-2 code BA = "BA" # Bosnia and Herzegovina country code CAF = "CAF" # Central African Republic country code flate2 = "flate2" diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index 37aaac42e0d..25e1f5827ad 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -160,9 +160,9 @@ pub struct OutgoingWebhook { /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, - #[serde(default, with = "custom_serde::iso8601")] /// The time at which webhook was sent + #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 76e280d6bc0..74fa75a2751 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -229,6 +229,7 @@ pub enum ProcessTrackerRunner { RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, + OutgoingWebhookRetryWorkflow, } #[cfg(test)] diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs index 735bd892508..9175823e5f9 100644 --- a/crates/diesel_models/src/query/events.rs +++ b/crates/diesel_models/src/query/events.rs @@ -14,6 +14,14 @@ impl EventNew { } impl Event { + pub async fn find_by_event_id(conn: &PgPooledConn, event_id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::event_id.eq(event_id.to_owned()), + ) + .await + } + pub async fn update( conn: &PgPooledConn, event_id: &str, diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index c2877535daa..c586bfecdb7 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -255,6 +255,9 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { ) } } + storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new( + workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow, + )), } }; diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index da14475f120..da9a7f3d163 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -135,7 +135,7 @@ where .map_into_boxed_body() } - Ok(api::ApplicationResponse::PaymenkLinkForm(boxed_payment_link_data)) => { + Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match api::build_payment_link_html(payment_link_data) { diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index cec563b9631..968181061a8 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -292,6 +292,10 @@ pub enum WebhooksFlowError { OutgoingWebhookEncodingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, + #[error("Failed to update outgoing webhook process tracker task")] + OutgoingWebhookProcessTrackerTaskUpdateFailed, + #[error("Failed to schedule retry attempt for outgoing webhook")] + OutgoingWebhookRetrySchedulingFailed, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 5af948bcf3e..096d5c88743 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -195,7 +195,7 @@ pub async fn intiate_payment_link_flow( js_script, css_script, }; - return Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + return Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))); }; @@ -225,7 +225,7 @@ pub async fn intiate_payment_link_flow( sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, }; - Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } @@ -574,7 +574,7 @@ pub async fn get_payment_link_status( js_script, css_script, }; - Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 622fed0738a..af9f94a0bdf 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1084,8 +1084,8 @@ pub async fn get_delete_tokenize_schedule_time( .await; let mapping = match redis_mapping { Ok(x) => x, - Err(err) => { - logger::info!("Redis Mapping Error: {}", err); + Err(error) => { + logger::info!(?error, "Redis Mapping Error"); process_data::PaymentMethodsPTMapping::default() } }; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 06030262fbc..80a0c285e41 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1167,34 +1167,3 @@ pub async fn get_refund_sync_process_schedule_time( Ok(process_tracker_utils::get_time_from_delta(time_delta)) } - -pub async fn retry_refund_sync_task( - db: &dyn db::StorageInterface, - connector: String, - merchant_id: String, - pt: storage::ProcessTracker, -) -> Result<(), errors::ProcessTrackerError> { - let schedule_time = - get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; - - match schedule_time { - Some(s_time) => { - let retry_schedule = db - .as_scheduler() - .retry_process(pt, s_time) - .await - .map_err(Into::into); - metrics::TASKS_RESET_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes("flow", "Refund")], - ); - retry_schedule - } - None => db - .as_scheduler() - .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) - .await - .map_err(Into::into), - } -} diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 9ec8de21f94..b3e04e72f33 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -32,6 +32,7 @@ use crate::{ events::{ api_logs::ApiEvent, outgoing_webhook_logs::{OutgoingWebhookEvent, OutgoingWebhookEventMetric}, + RawEvent, }, logger, routes::{app::AppStateInfo, lock_utils, metrics::request::add_attributes, AppState}, @@ -43,15 +44,13 @@ use crate::{ transformers::{ForeignInto, ForeignTryInto}, }, utils::{self as helper_utils, generate_id, OptionExt, ValueExt}, + workflows::outgoing_webhook_retry, }; const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; const MERCHANT_ID: &str = "merchant_id"; -pub async fn payments_incoming_webhook_flow< - W: types::OutgoingWebhookType, - Ctx: PaymentMethodRetrieve, ->( +pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -169,7 +168,7 @@ pub async fn payments_incoming_webhook_flow< // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -196,7 +195,7 @@ pub async fn payments_incoming_webhook_flow< #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] -pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn refunds_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -275,7 +274,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>( if let Some(outgoing_event_type) = event_type { let refund_response: api_models::refunds::RefundResponse = updated_refund.clone().foreign_into(); - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -414,7 +413,7 @@ pub async fn get_or_update_dispute_object( } } -pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn mandates_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -471,7 +470,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -496,7 +495,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn disputes_incoming_webhook_flow( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -538,7 +537,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( let disputes_response = Box::new(dispute_object.clone().foreign_into()); let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -562,7 +561,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( } } -async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( +async fn bank_transfer_webhook_flow<Ctx: PaymentMethodRetrieve>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -624,7 +623,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentM // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { - create_event_and_trigger_outgoing_webhook::<W>( + create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, @@ -649,53 +648,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentM #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn create_event_and_trigger_appropriate_outgoing_webhook( - state: AppState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - event_type: enums::EventType, - event_class: enums::EventClass, - intent_reference_id: Option<String>, - primary_object_id: String, - primary_object_type: enums::EventObjectType, - content: api::OutgoingWebhookContent, -) -> CustomResult<(), errors::ApiErrorResponse> { - match merchant_account.get_compatible_connector() { - #[cfg(feature = "stripe")] - Some(api_models::enums::Connector::Stripe) => { - create_event_and_trigger_outgoing_webhook::<stripe_webhooks::StripeOutgoingWebhook>( - state.clone(), - merchant_account, - business_profile, - event_type, - event_class, - intent_reference_id, - primary_object_id, - primary_object_type, - content, - ) - .await - } - _ => { - create_event_and_trigger_outgoing_webhook::<api_models::webhooks::OutgoingWebhook>( - state.clone(), - merchant_account, - business_profile, - event_type, - event_class, - intent_reference_id, - primary_object_id, - primary_object_type, - content, - ) - .await - } - } -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhookType>( +pub(crate) async fn create_event_and_trigger_outgoing_webhook( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, @@ -706,6 +659,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook primary_object_type: enums::EventObjectType, content: api::OutgoingWebhookContent, ) -> CustomResult<(), errors::ApiErrorResponse> { + let merchant_id = business_profile.merchant_id.clone(); let event_id = format!("{primary_object_id}_{event_type}"); let new_event = storage::EventNew { event_id: event_id.clone(), @@ -723,7 +677,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook Ok(event) => Ok(event), Err(error) => { if error.current_context().is_db_unique_violation() { - logger::info!("Merchant already notified about the event {event_id}"); + logger::debug!("Event `{event_id}` already exists in the database"); return Ok(()); } else { logger::error!(event_insertion_failure=?error); @@ -736,57 +690,132 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook if state.conf.webhooks.outgoing_enabled { let outgoing_webhook = api::OutgoingWebhook { - merchant_id: merchant_account.merchant_id.clone(), + merchant_id: merchant_id.clone(), event_id: event.event_id.clone(), event_type: event.event_type, content: content.clone(), timestamp: event.created_at, }; - let state_clone = state.clone(); + + let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker( + &*state.store, + &business_profile, + &event, + ) + .await + .map_err(|error| { + logger::error!( + ?error, + "Failed to add outgoing webhook retry task to process tracker" + ); + error + }) + .ok(); + // Using a tokio spawn here and not arbiter because not all caller of this function // may have an actix arbiter - tokio::spawn(async move { - let mut error = None; - let result = - trigger_webhook_to_merchant::<W>(business_profile, outgoing_webhook, state).await; - - if let Err(e) = result { - error.replace( - serde_json::to_value(e.current_context()) - .into_report() - .attach_printable("Failed to serialize json error response") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .ok() - .into(), - ); - logger::error!(?e); - } - let outgoing_webhook_event_type = content.get_outgoing_webhook_event_type(); - let webhook_event = OutgoingWebhookEvent::new( - merchant_account.merchant_id.clone(), - event.event_id.clone(), - event_type, - outgoing_webhook_event_type, - error, - ); - match webhook_event.clone().try_into() { - Ok(event) => { - state_clone.event_handler().log_event(event); - } - Err(err) => { - logger::error!(error=?err, event=?webhook_event, "Error Logging Outgoing Webhook Event"); - } + tokio::spawn( + async move { + trigger_appropriate_webhook_and_raise_event( + state, + merchant_account, + business_profile, + outgoing_webhook, + types::WebhookDeliveryAttempt::InitialAttempt, + content, + event.event_id, + event_type, + process_tracker, + ) + .await; } - }.in_current_span()); + .in_current_span(), + ); } Ok(()) } -pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( +#[allow(clippy::too_many_arguments)] +pub(crate) async fn trigger_appropriate_webhook_and_raise_event( + state: AppState, + merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, - webhook: api::OutgoingWebhook, + outgoing_webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + content: api::OutgoingWebhookContent, + event_id: String, + event_type: enums::EventType, + process_tracker: Option<storage::ProcessTracker>, +) { + match merchant_account.get_compatible_connector() { + #[cfg(feature = "stripe")] + Some(api_models::enums::Connector::Stripe) => { + trigger_webhook_and_raise_event::<stripe_webhooks::StripeOutgoingWebhook>( + state, + business_profile, + outgoing_webhook, + delivery_attempt, + content, + event_id, + event_type, + process_tracker, + ) + .await + } + _ => { + trigger_webhook_and_raise_event::<api_models::webhooks::OutgoingWebhook>( + state, + business_profile, + outgoing_webhook, + delivery_attempt, + content, + event_id, + event_type, + process_tracker, + ) + .await + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn trigger_webhook_and_raise_event<W: types::OutgoingWebhookType>( + state: AppState, + business_profile: diesel_models::business_profile::BusinessProfile, + outgoing_webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + content: api::OutgoingWebhookContent, + event_id: String, + event_type: enums::EventType, + process_tracker: Option<storage::ProcessTracker>, +) { + let merchant_id = business_profile.merchant_id.clone(); + let trigger_webhook_result = trigger_webhook_to_merchant::<W>( + state.clone(), + business_profile, + outgoing_webhook, + delivery_attempt, + process_tracker, + ) + .await; + + raise_webhooks_analytics_event( + state, + trigger_webhook_result, + content, + &merchant_id, + &event_id, + event_type, + ); +} + +async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( state: AppState, + business_profile: diesel_models::business_profile::BusinessProfile, + webhook: api::OutgoingWebhook, + delivery_attempt: types::WebhookDeliveryAttempt, + process_tracker: Option<storage::ProcessTracker>, ) -> CustomResult<(), errors::WebhooksFlowError> { let webhook_details_json = business_profile .webhook_details @@ -843,40 +872,135 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( ); logger::debug!(outgoing_webhook_response=?response); - match response { - Err(e) => { - // [#217]: Schedule webhook for retry. - Err(e).change_context(errors::WebhooksFlowError::CallToMerchantFailed)?; - } - Ok(res) => { - if res.status().is_success() { - metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - business_profile.merchant_id.clone(), - )], - ); - let update_event = storage::EventUpdate::UpdateWebhookNotified { - is_webhook_notified: Some(true), - }; - state + let api_client_error_handler = + |client_error: error_stack::Report<errors::ApiClientError>, + delivery_attempt: types::WebhookDeliveryAttempt| { + let error = + client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed); + logger::error!( + ?error, + ?delivery_attempt, + "An error occurred when sending webhook to merchant" + ); + }; + let success_response_handler = + |state: AppState, + merchant_id: String, + outgoing_webhook_event_id: String, + process_tracker: Option<storage::ProcessTracker>, + business_status: &'static str| async move { + metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], + ); + + let update_event = storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified: Some(true), + }; + state + .store + .update_event(outgoing_webhook_event_id, update_event) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)?; + + match process_tracker { + Some(process_tracker) => state .store - .update_event(outgoing_webhook_event_id, update_event) + .as_scheduler() + .finish_process_with_business_status(process_tracker, business_status.into()) .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)?; - } else { - metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - business_profile.merchant_id.clone(), - )], - ); - // [#217]: Schedule webhook for retry. - Err(errors::WebhooksFlowError::NotReceivedByMerchant).into_report()?; + .change_context( + errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, + ), + None => Ok(()), + } + }; + let error_response_handler = |merchant_id: String, + delivery_attempt: types::WebhookDeliveryAttempt, + status_code: u16, + log_message: &'static str| { + metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], + ); + + let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant); + logger::warn!(?error, ?delivery_attempt, ?status_code, %log_message); + }; + + match delivery_attempt { + types::WebhookDeliveryAttempt::InitialAttempt => match response { + Err(client_error) => api_client_error_handler(client_error, delivery_attempt), + Ok(response) => { + if response.status().is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + outgoing_webhook_event_id, + process_tracker, + "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id, + delivery_attempt, + response.status().as_u16(), + "Ignoring error when sending webhook to merchant", + ); + } + } + }, + types::WebhookDeliveryAttempt::AutomaticRetry => { + let process_tracker = process_tracker + .get_required_value("process_tracker") + .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed) + .attach_printable("`process_tracker` is unavailable in automatic retry flow")?; + match response { + Err(client_error) => { + api_client_error_handler(client_error, delivery_attempt); + // Schedule a retry attempt for webhook delivery + outgoing_webhook_retry::retry_webhook_delivery_task( + &*state.store, + &business_profile.merchant_id, + process_tracker, + ) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed, + )?; + } + Ok(response) => { + if response.status().is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + outgoing_webhook_event_id, + Some(process_tracker), + "COMPLETED_BY_PT", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id.clone(), + delivery_attempt, + response.status().as_u16(), + "An error occurred when sending webhook to merchant", + ); + // Schedule a retry attempt for webhook delivery + outgoing_webhook_retry::retry_webhook_delivery_task( + &*state.store, + &business_profile.merchant_id, + process_tracker, + ) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed, + )?; + } + } } } } @@ -884,6 +1008,48 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( Ok(()) } +fn raise_webhooks_analytics_event( + state: AppState, + trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, + content: api::OutgoingWebhookContent, + merchant_id: &str, + event_id: &str, + event_type: enums::EventType, +) { + let error = if let Err(error) = trigger_webhook_result { + logger::error!(?error, "Failed to send webhook to merchant"); + + serde_json::to_value(error.current_context()) + .into_report() + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .map_err(|error| { + logger::error!(?error, "Failed to serialize outgoing webhook error as JSON"); + error + }) + .ok() + } else { + None + }; + + let outgoing_webhook_event_content = content.get_outgoing_webhook_event_content(); + let webhook_event = OutgoingWebhookEvent::new( + merchant_id.to_owned(), + event_id.to_owned(), + event_type, + outgoing_webhook_event_content, + error, + ); + + match RawEvent::try_from(webhook_event.clone()) { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(error) => { + logger::error!(?error, event=?webhook_event, "Error logging outgoing webhook event"); + } + } +} + pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( flow: &impl router_env::types::FlowMetric, state: AppState, @@ -1196,7 +1362,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr })?; match flow_type { - api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow::<W, Ctx>( + api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow::<Ctx>( state.clone(), merchant_account, business_profile, @@ -1207,7 +1373,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for payments failed")?, - api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow::<W>( + api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1220,7 +1386,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for refunds failed")?, - api::WebhookFlow::Dispute => disputes_incoming_webhook_flow::<W>( + api::WebhookFlow::Dispute => disputes_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1233,7 +1399,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr .await .attach_printable("Incoming webhook flow for disputes failed")?, - api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow::<W, Ctx>( + api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow::<Ctx>( state.clone(), merchant_account, business_profile, @@ -1246,7 +1412,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, - api::WebhookFlow::Mandate => mandates_incoming_webhook_flow::<W>( + api::WebhookFlow::Mandate => mandates_incoming_webhook_flow( state.clone(), merchant_account, business_profile, @@ -1380,3 +1546,68 @@ async fn fetch_optional_mca_and_connector( Ok((None, connector)) } } + +pub async fn add_outgoing_webhook_retry_task_to_process_tracker( + db: &dyn StorageInterface, + business_profile: &diesel_models::business_profile::BusinessProfile, + event: &storage::Event, +) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time( + db, + &business_profile.merchant_id, + 0, + ) + .await + .ok_or(errors::StorageError::ValueNotFound( + "Process tracker schedule time".into(), // Can raise a better error here + )) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; + + let tracking_data = types::OutgoingWebhookTrackingData { + merchant_id: business_profile.merchant_id.clone(), + business_profile_id: business_profile.profile_id.clone(), + event_type: event.event_type, + event_class: event.event_class, + primary_object_id: event.primary_object_id.clone(), + primary_object_type: event.primary_object_type, + }; + + let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow; + let task = "OUTGOING_WEBHOOK_RETRY"; + let tag = ["OUTGOING_WEBHOOKS"]; + let process_tracker_id = scheduler::utils::get_process_tracker_id( + runner, + task, + &event.primary_object_id, + &business_profile.merchant_id, + ); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + tracking_data, + schedule_time, + ) + .map_err(errors::StorageError::from)?; + + match db.insert_process(process_tracker_entry).await { + Ok(process_tracker) => { + crate::routes::metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[add_attributes("flow", "OutgoingWebhookRetry")], + ); + Ok(process_tracker) + } + Err(error) => { + crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add( + &metrics::CONTEXT, + 1, + &[add_attributes("flow", "OutgoingWebhookRetry")], + ); + Err(error) + } + } +} diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs index a0e999971c5..a6bc7fbc23e 100644 --- a/crates/router/src/core/webhooks/types.rs +++ b/crates/router/src/core/webhooks/types.rs @@ -3,7 +3,7 @@ use common_utils::{crypto::SignMessage, ext_traits::Encode}; use error_stack::ResultExt; use serde::Serialize; -use crate::{core::errors, headers, services::request::Maskable}; +use crate::{core::errors, headers, services::request::Maskable, types::storage::enums}; pub trait OutgoingWebhookType: Serialize + From<webhooks::OutgoingWebhook> + Sync + Send + std::fmt::Debug + 'static @@ -43,3 +43,19 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook { header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into())) } } + +#[derive(Debug, Clone, Copy)] +pub(crate) enum WebhookDeliveryAttempt { + InitialAttempt, + AutomaticRetry, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct OutgoingWebhookTrackingData { + pub(crate) merchant_id: String, + pub(crate) business_profile_id: String, + pub(crate) event_type: enums::EventType, + pub(crate) event_class: enums::EventClass, + pub(crate) primary_object_id: String, + pub(crate) primary_object_type: enums::EventObjectType, +} diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index af99d6a8e38..28fe4ef32d6 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -14,6 +14,12 @@ pub trait EventInterface { &self, event: storage::EventNew, ) -> CustomResult<storage::Event, errors::StorageError>; + + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError>; + async fn update_event( &self, event_id: String, @@ -31,6 +37,19 @@ impl EventInterface for Store { let conn = connection::pg_connection_write(self).await?; event.insert(&conn).await.map_err(Into::into).into_report() } + + #[instrument(skip_all)] + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Event::find_by_event_id(&conn, event_id) + .await + .map_err(Into::into) + .into_report() + } + #[instrument(skip_all)] async fn update_event( &self, @@ -74,6 +93,24 @@ impl EventInterface for MockDb { Ok(stored_event) } + + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + let locked_events = self.events.lock().await; + locked_events + .iter() + .find(|event| event.event_id == event_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No event available with event_id = {event_id}" + )) + .into(), + ) + } + async fn update_event( &self, event_id: String, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 35c93f334ab..8ba977befcc 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -487,6 +487,13 @@ impl EventInterface for KafkaStore { self.diesel_store.insert_event(event).await } + async fn find_event_by_event_id( + &self, + event_id: &str, + ) -> CustomResult<storage::Event, errors::StorageError> { + self.diesel_store.find_event_by_event_id(event_id).await + } + async fn update_event( &self, event_id: String, diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs index c2b2366fac9..bc5907b0cc4 100644 --- a/crates/router/src/events/outgoing_webhook_logs.rs +++ b/crates/router/src/events/outgoing_webhook_logs.rs @@ -43,10 +43,10 @@ pub enum OutgoingWebhookEventContent { }, } pub trait OutgoingWebhookEventMetric { - fn get_outgoing_webhook_event_type(&self) -> Option<OutgoingWebhookEventContent>; + fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>; } impl OutgoingWebhookEventMetric for OutgoingWebhookContent { - fn get_outgoing_webhook_event_type(&self) -> Option<OutgoingWebhookEventContent> { + fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> { match self { Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment { payment_id: payment_payload.payment_id.clone(), diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 60f6dd74186..28b3e0db211 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -224,7 +224,8 @@ pub async fn attach_dispute_evidence( )) .await } -/// Diputes - Retrieve Dispute + +/// Disputes - Retrieve Dispute #[utoipa::path( get, path = "/disputes/evidence/{dispute_id}", diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 32f2a614d03..780dd51bbde 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -118,7 +118,9 @@ counter_metric!(AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYOUT_COUNT, GLOBAL_METER); +// Scheduler / Process Tracker related metrics counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker +counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow pub mod request; diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index 30db586b7f9..029c1c61f24 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -60,7 +60,7 @@ pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 { | ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::Form(_) - | ApplicationResponse::PaymenkLinkForm(_) + | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) | ApplicationResponse::JsonWithHeaders(_) => 200, ApplicationResponse::JsonForRedirection(_) => 302, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 10239834669..f01b0ffc346 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -845,7 +845,7 @@ pub enum ApplicationResponse<R> { TextPlain(String), JsonForRedirection(api::RedirectionResponse), Form(Box<RedirectionFormData>), - PaymenkLinkForm(Box<PaymentLinkAction>), + PaymentLinkForm(Box<PaymentLinkAction>), FileData((Vec<u8>, mime::Mime)), JsonWithHeaders((R, Vec<(String, String)>)), } @@ -1186,7 +1186,7 @@ where .map_into_boxed_body() } - Ok(ApplicationResponse::PaymenkLinkForm(boxed_payment_link_data)) => { + Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match build_payment_link_html(payment_link_data) { diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f218751204b..473afd1bf65 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -802,21 +802,19 @@ where if let Some(event_type) = event_type { tokio::spawn( async move { - Box::pin( - webhooks_core::create_event_and_trigger_appropriate_outgoing_webhook( - m_state, - merchant_account, - business_profile, - event_type, - diesel_models::enums::EventClass::Payments, - None, - payment_id, - diesel_models::enums::EventObjectType::PaymentDetails, - webhooks::OutgoingWebhookContent::PaymentDetails( - payments_response_json, - ), + Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( + m_state, + merchant_account, + business_profile, + event_type, + diesel_models::enums::EventClass::Payments, + None, + payment_id, + diesel_models::enums::EventObjectType::PaymentDetails, + webhooks::OutgoingWebhookContent::PaymentDetails( + payments_response_json, ), - ) + )) .await } .in_current_span(), diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index deb5bf785fa..6158031079c 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -1,5 +1,6 @@ #[cfg(feature = "email")] pub mod api_key_expiry; +pub mod outgoing_webhook_retry; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs new file mode 100644 index 00000000000..6ce7e2454f8 --- /dev/null +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -0,0 +1,374 @@ +use api_models::{ + enums::EventType, + webhooks::{OutgoingWebhook, OutgoingWebhookContent}, +}; +use common_utils::ext_traits::{StringExt, ValueExt}; +use error_stack::ResultExt; +use router_env::tracing::{self, instrument}; +use scheduler::{ + consumer::{self, workflows::ProcessTrackerWorkflow}, + types::process_data, + utils as scheduler_utils, +}; + +use crate::{ + core::webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData}, + db::StorageInterface, + errors, logger, + routes::AppState, + types::{domain, storage}, +}; + +pub struct OutgoingWebhookRetryWorkflow; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow<AppState> for OutgoingWebhookRetryWorkflow { + #[instrument(skip_all)] + async fn execute_workflow<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let tracking_data: OutgoingWebhookTrackingData = process + .tracking_data + .clone() + .parse_value("OutgoingWebhookTrackingData")?; + + let db = &*state.store; + let key_store = db + .get_merchant_key_store_by_merchant_id( + &tracking_data.merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await?; + let merchant_account = db + .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store) + .await?; + let business_profile = db + .find_business_profile_by_profile_id(&tracking_data.business_profile_id) + .await?; + + let event_id = format!( + "{}_{}", + tracking_data.primary_object_id, tracking_data.event_type + ); + let event = db.find_event_by_event_id(&event_id).await?; + + let (content, event_type) = get_outgoing_webhook_content_and_event_type( + state.clone(), + merchant_account.clone(), + key_store, + &tracking_data, + ) + .await?; + + match event_type { + // Resource status is same as the event type of the current event + Some(event_type) if event_type == tracking_data.event_type => { + let outgoing_webhook = OutgoingWebhook { + merchant_id: tracking_data.merchant_id.clone(), + event_id: event_id.clone(), + event_type, + content: content.clone(), + timestamp: event.created_at, + }; + + webhooks_core::trigger_appropriate_webhook_and_raise_event( + state.clone(), + merchant_account, + business_profile, + outgoing_webhook, + webhooks_core::types::WebhookDeliveryAttempt::AutomaticRetry, + content, + event_id, + event_type, + Some(process), + ) + .await; + } + // Resource status has changed since the event was created, finish task + _ => { + logger::warn!( + %event_id, + "The current status of the resource `{}` (event type: {:?}) and the status of \ + the resource when the event was created (event type: {:?}) differ, finishing task", + tracking_data.primary_object_id, + event_type, + tracking_data.event_type + ); + db.as_scheduler() + .finish_process_with_business_status( + process.clone(), + "RESOURCE_STATUS_MISMATCH".to_string(), + ) + .await?; + } + } + + Ok(()) + } + + #[instrument(skip_all)] + async fn error_handler<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + error: errors::ProcessTrackerError, + ) -> errors::CustomResult<(), errors::ProcessTrackerError> { + consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await + } +} + +/// Get the schedule time for the specified retry count. +/// +/// The schedule time can be configured in configs with this key: `pt_mapping_outgoing_webhooks`. +/// +/// ```json +/// { +/// "default_mapping": { +/// "start_after": 60, +/// "frequency": [300], +/// "count": [5] +/// }, +/// "custom_merchant_mapping": { +/// "merchant_id1": { +/// "start_after": 30, +/// "frequency": [300], +/// "count": [2] +/// } +/// } +/// } +/// ``` +/// +/// This configuration value represents: +/// - `default_mapping.start_after`: The first retry attempt should happen after 60 seconds by +/// default. +/// - `default_mapping.frequency` and `count`: The next 5 retries should have an interval of 300 +/// seconds between them by default. +/// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant +/// with merchant ID `merchant_id1`. +#[instrument(skip_all)] +pub(crate) async fn get_webhook_delivery_retry_schedule_time( + db: &dyn StorageInterface, + merchant_id: &str, + retry_count: i32, +) -> Option<time::PrimitiveDateTime> { + let key = "pt_mapping_outgoing_webhooks"; + + let result = db + .find_config_by_key(key) + .await + .map(|value| value.config) + .and_then(|config| { + config + .parse_struct("OutgoingWebhookRetryProcessTrackerMapping") + .change_context(errors::StorageError::DeserializationFailed) + }); + let mapping = result.map_or_else( + |error| { + if error.current_context().is_db_not_found() { + logger::debug!("Outgoing webhooks retry config `{key}` not found, ignoring"); + } else { + logger::error!( + ?error, + "Failed to read outgoing webhooks retry config `{key}`" + ); + } + process_data::OutgoingWebhookRetryProcessTrackerMapping::default() + }, + |mapping| { + logger::debug!(?mapping, "Using custom outgoing webhooks retry config"); + mapping + }, + ); + + let time_delta = scheduler_utils::get_outgoing_webhook_retry_schedule_time( + mapping, + merchant_id, + retry_count, + ); + + scheduler_utils::get_time_from_delta(time_delta) +} + +/// Schedule the webhook delivery task for retry +#[instrument(skip_all)] +pub(crate) async fn retry_webhook_delivery_task( + db: &dyn StorageInterface, + merchant_id: &str, + process: storage::ProcessTracker, +) -> errors::CustomResult<(), errors::StorageError> { + let schedule_time = + get_webhook_delivery_retry_schedule_time(db, merchant_id, process.retry_count + 1).await; + + match schedule_time { + Some(schedule_time) => { + db.as_scheduler() + .retry_process(process, schedule_time) + .await + } + None => { + db.as_scheduler() + .finish_process_with_business_status(process, "RETRIES_EXCEEDED".to_string()) + .await + } + } +} + +#[instrument(skip_all)] +async fn get_outgoing_webhook_content_and_event_type( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + tracking_data: &OutgoingWebhookTrackingData, +) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> { + use api_models::{ + mandates::MandateId, + payments::{HeaderPayload, PaymentIdType, PaymentsResponse, PaymentsRetrieveRequest}, + refunds::{RefundResponse, RefundsRetrieveRequest}, + }; + + use crate::{ + core::{ + disputes::retrieve_dispute, + mandate::get_mandate, + payment_methods::Oss, + payments::{payments_core, CallConnectorAction, PaymentStatus}, + refunds::refund_retrieve_core, + }, + services::{ApplicationResponse, AuthFlow}, + types::{ + api::{DisputeId, PSync}, + transformers::ForeignFrom, + }, + }; + + match tracking_data.event_class { + diesel_models::enums::EventClass::Payments => { + let payment_id = tracking_data.primary_object_id.clone(); + let request = PaymentsRetrieveRequest { + resource_id: PaymentIdType::PaymentIntentId(payment_id), + merchant_id: Some(tracking_data.merchant_id.clone()), + force_sync: false, + ..Default::default() + }; + + let payments_response = match payments_core::<PSync, PaymentsResponse, _, _, _, Oss>( + state, + merchant_account, + key_store, + PaymentStatus, + request, + AuthFlow::Client, + CallConnectorAction::Avoid, + None, + HeaderPayload::default(), + ) + .await? + { + ApplicationResponse::Json(payments_response) + | ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + Ok(payments_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + }?; + let event_type = Option::<EventType>::foreign_from(payments_response.status); + logger::debug!(current_resource_status=%payments_response.status); + + Ok(( + OutgoingWebhookContent::PaymentDetails(payments_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Refunds => { + let refund_id = tracking_data.primary_object_id.clone(); + let request = RefundsRetrieveRequest { + refund_id, + force_sync: Some(false), + merchant_connector_details: None, + }; + + let refund = refund_retrieve_core(state, merchant_account, key_store, request).await?; + let event_type = Option::<EventType>::foreign_from(refund.refund_status); + logger::debug!(current_resource_status=%refund.refund_status); + let refund_response = RefundResponse::foreign_from(refund); + + Ok(( + OutgoingWebhookContent::RefundDetails(refund_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Disputes => { + let dispute_id = tracking_data.primary_object_id.clone(); + let request = DisputeId { dispute_id }; + + let dispute_response = + match retrieve_dispute(state, merchant_account, request).await? { + ApplicationResponse::Json(dispute_response) + | ApplicationResponse::JsonWithHeaders((dispute_response, _)) => { + Ok(dispute_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + } + .map(Box::new)?; + let event_type = Some(EventType::foreign_from(dispute_response.dispute_status)); + logger::debug!(current_resource_status=%dispute_response.dispute_status); + + Ok(( + OutgoingWebhookContent::DisputeDetails(dispute_response), + event_type, + )) + } + + diesel_models::enums::EventClass::Mandates => { + let mandate_id = tracking_data.primary_object_id.clone(); + let request = MandateId { mandate_id }; + + let mandate_response = + match get_mandate(state, merchant_account, key_store, request).await? { + ApplicationResponse::Json(mandate_response) + | ApplicationResponse::JsonWithHeaders((mandate_response, _)) => { + Ok(mandate_response) + } + ApplicationResponse::StatusOk + | ApplicationResponse::TextPlain(_) + | ApplicationResponse::JsonForRedirection(_) + | ApplicationResponse::Form(_) + | ApplicationResponse::PaymentLinkForm(_) + | ApplicationResponse::FileData(_) => { + Err(errors::ProcessTrackerError::ResourceFetchingFailed { + resource_name: tracking_data.primary_object_id.clone(), + }) + } + } + .map(Box::new)?; + let event_type = Option::<EventType>::foreign_from(mandate_response.status); + logger::debug!(current_resource_status=%mandate_response.status); + + Ok(( + OutgoingWebhookContent::MandateDetails(mandate_response), + event_type, + )) + } + } +} diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 92057b08899..c328a67a0ff 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -247,12 +247,12 @@ pub async fn get_sync_process_schedule_time( }); let mapping = match mapping { Ok(x) => x, - Err(err) => { - logger::info!("Redis Mapping Error: {}", err); + Err(error) => { + logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; - let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count + 1); + let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) } @@ -267,7 +267,7 @@ pub async fn retry_sync_task( pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = - get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; + get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs index d5299493b1f..267305c37f9 100644 --- a/crates/scheduler/src/consumer/types/process_data.rs +++ b/crates/scheduler/src/consumer/types/process_data.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use diesel_models::enums; use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Clone)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct RetryMapping { pub start_after: i32, pub frequency: Vec<i32>, @@ -11,7 +11,6 @@ pub struct RetryMapping { } #[derive(Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] pub struct ConnectorPTMapping { pub default_mapping: RetryMapping, pub custom_merchant_mapping: HashMap<String, RetryMapping>, @@ -33,7 +32,6 @@ impl Default for ConnectorPTMapping { } #[derive(Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] pub struct PaymentMethodsPTMapping { pub default_mapping: RetryMapping, pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>, @@ -53,3 +51,43 @@ impl Default for PaymentMethodsPTMapping { } } } + +/// Configuration for outgoing webhook retries. +#[derive(Debug, Serialize, Deserialize)] +pub struct OutgoingWebhookRetryProcessTrackerMapping { + /// Default (fallback) retry configuration used when no merchant-specific retry configuration + /// exists. + pub default_mapping: RetryMapping, + + /// Merchant-specific retry configuration. + pub custom_merchant_mapping: HashMap<String, RetryMapping>, +} + +impl Default for OutgoingWebhookRetryProcessTrackerMapping { + fn default() -> Self { + Self { + default_mapping: RetryMapping { + // 1st attempt happens after 1 minute + start_after: 60, + + frequency: vec![ + // 2nd and 3rd attempts happen at intervals of 5 minutes each + 60 * 5, + // 4th, 5th, 6th, 7th and 8th attempts happen at intervals of 10 minutes each + 60 * 10, + // 9th, 10th, 11th, 12th and 13th attempts happen at intervals of 1 hour each + 60 * 60, + // 14th, 15th and 16th attempts happen at intervals of 6 hours each + 60 * 60 * 6, + ], + count: vec![ + 2, // 2nd and 3rd attempts + 5, // 4th, 5th, 6th, 7th and 8th attempts + 5, // 9th, 10th, 11th, 12th and 13th attempts + 3, // 14th, 15th and 16th attempts + ], + }, + custom_merchant_mapping: HashMap::new(), + } + } +} diff --git a/crates/scheduler/src/db/queue.rs b/crates/scheduler/src/db/queue.rs index 2c02b405d81..a463111ab3b 100644 --- a/crates/scheduler/src/db/queue.rs +++ b/crates/scheduler/src/db/queue.rs @@ -144,7 +144,7 @@ impl QueueInterface for MockDb { ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { // [#172]: Implement function for `MockDb` Err(ProcessTrackerError::ResourceFetchingFailed { - resource_name: "consumer_tasks", + resource_name: "consumer_tasks".to_string(), })? } diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs index 78a0bdee624..6a14bd2611e 100644 --- a/crates/scheduler/src/errors.rs +++ b/crates/scheduler/src/errors.rs @@ -34,7 +34,7 @@ pub enum ProcessTrackerError { #[error("Failed to fetch processes from database")] ProcessFetchingFailed, #[error("Failed while fetching: {resource_name}")] - ResourceFetchingFailed { resource_name: &'static str }, + ResourceFetchingFailed { resource_name: String }, #[error("Failed while executing: {flow}")] FlowExecutionError { flow: &'static str }, #[error("Not Implemented")] diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 174efd637e9..48d02f7fced 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -342,22 +342,46 @@ pub fn get_pm_schedule_time( } } -/// Get the delay based on the retry count -fn get_delay<'a>( +pub fn get_outgoing_webhook_retry_schedule_time( + mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping, + merchant_name: &str, retry_count: i32, - mut array: impl Iterator<Item = (&'a i32, &'a i32)>, ) -> Option<i32> { - match array.next() { - Some(ele) => { - let v = retry_count - ele.0; - if v <= 0 { - Some(*ele.1) - } else { - get_delay(v, array) - } + let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_name) { + Some(map) => map.clone(), + None => mapping.default_mapping, + }; + + // For first try, get the `start_after` time + if retry_count == 0 { + Some(retry_mapping.start_after) + } else { + get_delay( + retry_count, + retry_mapping + .count + .iter() + .zip(retry_mapping.frequency.iter()), + ) + } +} + +/// Get the delay based on the retry count +fn get_delay<'a>(retry_count: i32, array: impl Iterator<Item = (&'a i32, &'a i32)>) -> Option<i32> { + // Preferably, fix this by using unsigned ints + if retry_count <= 0 { + return None; + } + + let mut cumulative_count = 0; + for (&count, &frequency) in array { + cumulative_count += count; + if cumulative_count >= retry_count { + return Some(frequency); } - None => None, } + + None } pub(crate) async fn lock_acquire_release<T, F, Fut>( @@ -392,3 +416,38 @@ where Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_delay() { + let count = [10, 5, 3, 2]; + let frequency = [300, 600, 1800, 3600]; + + let retry_counts_and_expected_delays = [ + (-4, None), + (-2, None), + (0, None), + (4, Some(300)), + (7, Some(300)), + (10, Some(300)), + (12, Some(600)), + (16, Some(1800)), + (18, Some(1800)), + (20, Some(3600)), + (24, None), + (30, None), + ]; + + for (retry_count, expected_delay) in retry_counts_and_expected_delays { + let delay = get_delay(retry_count, count.iter().zip(frequency.iter())); + + assert_eq!( + delay, expected_delay, + "Delay and expected delay differ for `retry_count` = {retry_count}" + ); + } + } +}
2024-02-27T08:30:01Z
## Description <!-- Describe your changes in detail --> This PR adds support for automatically retrying outgoing webhook deliveries in case of failed deliveries, with the aid of the scheduler (process tracker). ### Behavior (Initial Delivery) The behavior when an outgoing webhook is being sent is: 1. During the initial webhook delivery attempt, a process tracker task is added before sending the webhook, since we launch the webhook delivery task on a background thread that we have no control over. The scheduled time for the task is determined from configuration (persisted in database/Redis), which has been explained later. 2. Next, we trigger the webhook to the merchant and an analytics event is raised, as before. 1. In case the initial delivery attempt succeeds, the process tracker task is marked completed. The end. 2. In case the initial delivery attempt fails, no further action is taken, the webhook delivery will be attempted again by the process tracker at the scheduled time. ### Behavior (Automatic Retry) 1. During the automatic retry attempt(s) from process tracker, the current information about the resource (about which the webhook is being sent) is fetched from the database and will be included in the webhook payload. 2. If the status of the resource is different than when the event for the webhook was created (the resource has now transitioned to another status), then the process tracker task is aborted with business status indicating the status mismatch. 3. When triggering the webhook to the merchant: 1. If the retry attempt succeeds, the process tracker task is marked completed. 2. If the retry attempt fails, the process tracker task is scheduled again for retry at the scheduled time determined from configuration. 3. If the number of retries exceeds the maximum number of retries, then the process tracker task is marked completed with business status indicating that retries exceeded. ### Configuring Retry Intervals The retry intervals for webhook deliveries are determined by runtime configuration (persisted in the database/Redis), using the key `pt_mapping_outgoing_webhooks`. In case the configuration value is not available in storage, a default configuration value is used, which is harcoded in the application: https://github.com/juspay/hyperswitch/blob/1d3bf5cf9ae800d4eba78c2ae03824c9a623ed87/crates/scheduler/src/consumer/types/process_data.rs#L69-L89 In case the default configuration needs to be overridden, it can be done so using the configuration create (or update) endpoint: ```shell curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{ "key": "pt_mapping_outgoing_webhooks", "value": "{\"default_mapping\":{\"start_after\":60,\"frequency\":[15,30],\"count\":[2,3]},\"custom_merchant_mapping\":{}}" }' ``` This would override the configuration for all merchants. Note that `frequency` and `start_after` are specified in seconds. If it needs to be overridden only for a specific merchant, then the `custom_merchant_mapping` field must have a similar object as `default_mapping`, keyed by the merchant ID: ```json { "default_mapping": { "start_after": 60, "frequency": [15, 30], "count": [2, 3] }, "custom_merchant_mapping": { "merchant_id1": { "start_after": 30, "frequency": [300], "count": [2] } } } ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #217. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> As of now, outgoing webhooks are supported for payments, refunds, disputes and mandates. I've extensively tested payments outgoing webhooks for the different cases, and done a sanity testing on disputes and refunds webhooks to verify that they are retried in case the initial delivery attempt fails. Incoming mandates webhooks are integrated for the GoCardless connector, but the integration is broken and I couldn't test mandates webhook retries. As for simulating failed webhook deliveries, the merchant webhook URL would have to be configured to a URL which does not accept `POST` requests. After a couple of failed retries, the URL can be updated to a valid URL to try out the case where the retried delivery attempt succeeds. Since the hardcoded default retry configuration spans multiple hours, I configured the application to use shorter intervals: ```shell curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{ "key": "pt_mapping_outgoing_webhooks", "value": "{\"default_mapping\":{\"start_after\":60,\"frequency\":[15,30],\"count\":[2,3]},\"custom_merchant_mapping\":{}}" }' ``` The `process_tracker` table can be queried for relevant record using this query: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' ORDER BY schedule_time DESC; ``` 1. If the initial delivery attempt is successful, the business status of the process tracker entry is set to `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`: ![Screenshot of process tracker entry where initial delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/f9c77bc5-4834-43dc-aa15-892d9ef2db28) 2. If one of the retried delivery attempts are successful, the business status of the process tracker entry is set to `COMPLETED_BY_PT`: ![Screenshot of process tracker entry where retried delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/7d3b6beb-3cbf-4aa6-8141-7481df8aea54) 4. If none of the delivery attempts are successful, the business status of the process tracker entry is set to `RETRIES_EXCEEDED`: ![Screenshot of process tracker entry where retries failed](https://github.com/juspay/hyperswitch/assets/22217505/aad8c1bb-837a-40f4-9bbf-db3169a4751e) In my case, the configured `count` was `[2,3]`, so the maximum number of retries turns out to be 2 + 3 = 5. As for testing refunds and disputes webhooks, the screenshots are attached below: 1. Refunds (note the `event_type` and `event_class` fields): ![Screenshot of failed refund webhook being retried](https://github.com/juspay/hyperswitch/assets/22217505/20cc14df-fa1f-49aa-911a-844bf103149b) 2. Disputes (note the `event_type` and `event_class` fields), the business status is `RESOURCE_STATUS_MISMATCH` since the dispute status changed since the time it was created to the time the webhook was being retried: ![Screenshot of dispute webhook being aborted due to status mismatch](https://github.com/juspay/hyperswitch/assets/22217505/965934a1-f42d-4bb4-9a4d-815e838fe6dc) In addition, successful and failed task additions should raise appropriate metrics (`TASKS_ADDED_COUNT` and `TASK_ADDITION_FAILURES_COUNT` respectively), and suitable logs are being thrown when delivering webhooks to the merchant fails, and when retry configs are being read from the database. The PR also adds unit tests for a scheduler utility function I refactored, which can be run using the command: ```shell cargo test --package scheduler --lib -- utils::tests ``` ![Screenshot of unit tests run](https://github.com/juspay/hyperswitch/assets/22217505/9481f100-3532-4846-97da-a935b915e609)
9917dd065444d66628039b19df7cd8e7d5c107db
As of now, outgoing webhooks are supported for payments, refunds, disputes and mandates. I've extensively tested payments outgoing webhooks for the different cases, and done a sanity testing on disputes and refunds webhooks to verify that they are retried in case the initial delivery attempt fails. Incoming mandates webhooks are integrated for the GoCardless connector, but the integration is broken and I couldn't test mandates webhook retries. As for simulating failed webhook deliveries, the merchant webhook URL would have to be configured to a URL which does not accept `POST` requests. After a couple of failed retries, the URL can be updated to a valid URL to try out the case where the retried delivery attempt succeeds. Since the hardcoded default retry configuration spans multiple hours, I configured the application to use shorter intervals: ```shell curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{ "key": "pt_mapping_outgoing_webhooks", "value": "{\"default_mapping\":{\"start_after\":60,\"frequency\":[15,30],\"count\":[2,3]},\"custom_merchant_mapping\":{}}" }' ``` The `process_tracker` table can be queried for relevant record using this query: ```sql SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' ORDER BY schedule_time DESC; ``` 1. If the initial delivery attempt is successful, the business status of the process tracker entry is set to `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`: ![Screenshot of process tracker entry where initial delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/f9c77bc5-4834-43dc-aa15-892d9ef2db28) 2. If one of the retried delivery attempts are successful, the business status of the process tracker entry is set to `COMPLETED_BY_PT`: ![Screenshot of process tracker entry where retried delivery attempt was successful](https://github.com/juspay/hyperswitch/assets/22217505/7d3b6beb-3cbf-4aa6-8141-7481df8aea54) 4. If none of the delivery attempts are successful, the business status of the process tracker entry is set to `RETRIES_EXCEEDED`: ![Screenshot of process tracker entry where retries failed](https://github.com/juspay/hyperswitch/assets/22217505/aad8c1bb-837a-40f4-9bbf-db3169a4751e) In my case, the configured `count` was `[2,3]`, so the maximum number of retries turns out to be 2 + 3 = 5. As for testing refunds and disputes webhooks, the screenshots are attached below: 1. Refunds (note the `event_type` and `event_class` fields): ![Screenshot of failed refund webhook being retried](https://github.com/juspay/hyperswitch/assets/22217505/20cc14df-fa1f-49aa-911a-844bf103149b) 2. Disputes (note the `event_type` and `event_class` fields), the business status is `RESOURCE_STATUS_MISMATCH` since the dispute status changed since the time it was created to the time the webhook was being retried: ![Screenshot of dispute webhook being aborted due to status mismatch](https://github.com/juspay/hyperswitch/assets/22217505/965934a1-f42d-4bb4-9a4d-815e838fe6dc) In addition, successful and failed task additions should raise appropriate metrics (`TASKS_ADDED_COUNT` and `TASK_ADDITION_FAILURES_COUNT` respectively), and suitable logs are being thrown when delivering webhooks to the merchant fails, and when retry configs are being read from the database. The PR also adds unit tests for a scheduler utility function I refactored, which can be run using the command: ```shell cargo test --package scheduler --lib -- utils::tests ``` ![Screenshot of unit tests run](https://github.com/juspay/hyperswitch/assets/22217505/9481f100-3532-4846-97da-a935b915e609)
[ ".typos.toml", "crates/api_models/src/webhooks.rs", "crates/diesel_models/src/process_tracker.rs", "crates/diesel_models/src/query/events.rs", "crates/router/src/bin/scheduler.rs", "crates/router/src/compatibility/wrap.rs", "crates/router/src/core/errors.rs", "crates/router/src/core/payment_link.rs", ...
juspay/hyperswitch
juspay__hyperswitch-3841
Bug: [FEATURE] : [Globalpay] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index ee62e8c2c2c..1e5413bc838 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -41,7 +41,7 @@ pub struct GlobalpayPaymentsRequest { /// Indicates whether the Merchant or the Payer initiated the creation of a transaction. pub initiator: Option<Initiator>, /// Indicates the source IP Address of the system used to create the transaction. - pub ip_address: Option<String>, + pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>, /// Indicates the language the transaction was executed in. In the format ISO-639-1 (alpha-2) /// or ISO-639-1 (alpha-2)_ISO-3166(alpha-2) pub language: Option<Language>, @@ -80,8 +80,8 @@ pub struct GlobalpayPaymentsRequest { #[derive(Debug, Serialize)] pub struct GlobalpayRefreshTokenRequest { pub app_id: Secret<String>, - pub nonce: String, - pub secret: String, + pub nonce: Secret<String>, + pub secret: Secret<String>, pub grant_type: String, } @@ -106,10 +106,10 @@ pub struct Device { /// Describes the receipts a device prints when processing a transaction. pub print_receipt_mode: Option<PrintReceiptMode>, /// The sequence number from the device used to align with processing platform. - pub sequence_number: Option<String>, + pub sequence_number: Option<Secret<String>>, /// A unique identifier for the physical device. This value persists with the device even if /// it is repurposed. - pub serial_number: Option<String>, + pub serial_number: Option<Secret<String>>, /// The time from the device in ISO8601 format pub time: Option<String>, } @@ -209,15 +209,15 @@ pub struct PaymentMethod { /// Indicates whether to execute the fingerprint signature functionality. pub fingerprint_mode: Option<FingerprintMode>, /// Specify the first name of the owner of the payment method. - pub first_name: Option<String>, + pub first_name: Option<Secret<String>>, /// Unique Global Payments generated id used to reference a stored payment method on the /// Global Payments system. Often referred to as the payment method token. This value can be /// used instead of payment method details such as a card number and expiry date. - pub id: Option<String>, + pub id: Option<Secret<String>>, /// Specify the surname of the owner of the payment method. - pub last_name: Option<String>, + pub last_name: Option<Secret<String>>, /// The full name of the owner of the payment method. - pub name: Option<String>, + pub name: Option<Secret<String>>, /// Contains the value a merchant wishes to appear on the payer's payment method statement /// for this transaction pub narrative: Option<String>, @@ -274,11 +274,11 @@ pub struct ThreeDs { pub struct BankTransfer { /// The number or reference for the payer's bank account. - pub account_number: Option<String>, + pub account_number: Option<Secret<String>>, pub bank: Option<Bank>, /// The number or reference for the check - pub check_reference: Option<String>, + pub check_reference: Option<Secret<String>>, /// The type of bank account associated with the payer's bank account. pub number_type: Option<NumberType>, /// Indicates how the transaction was authorized by the merchant. @@ -289,7 +289,7 @@ pub struct BankTransfer { pub struct Bank { pub address: Option<Address>, /// The local identifier code for the bank. - pub code: Option<String>, + pub code: Option<Secret<String>>, /// The name of the bank. pub name: Option<String>, } @@ -297,17 +297,17 @@ pub struct Bank { #[derive(Debug, Serialize, Deserialize)] pub struct Address { /// Merchant defined field common to all transactions that are part of the same order. - pub city: Option<String>, + pub city: Option<Secret<String>>, /// The country in ISO-3166-1(alpha-2 code) format. pub country: Option<String>, /// First line of the address. - pub line_1: Option<String>, + pub line_1: Option<Secret<String>>, /// Second line of the address. - pub line_2: Option<String>, + pub line_2: Option<Secret<String>>, /// Third line of the address. - pub line_3: Option<String>, + pub line_3: Option<Secret<String>>, /// The city or town of the address. - pub postal_code: Option<String>, + pub postal_code: Option<Secret<String>>, /// The state or region of the address. ISO 3166-2 minus the country code itself. For /// example, US Illinois = IL, or in the case of GB counties Wiltshire = WI or Aberdeenshire /// = ABD @@ -319,7 +319,7 @@ pub struct Card { /// The card providers description of their card product. pub account_type: Option<String>, /// Code generated when the card is successfully authorized. - pub authcode: Option<String>, + pub authcode: Option<Secret<String>>, /// First line of the address associated with the card. pub avs_address: Option<String>, /// Postal code of the address associated with the card. @@ -340,11 +340,11 @@ pub struct Card { /// The the card account number used to authorize the transaction. Also known as PAN. pub number: cards::CardNumber, /// Contains the pin block info, relating to the pin code the Payer entered. - pub pin_block: Option<String>, + pub pin_block: Option<Secret<String>>, /// The full card tag data for an EMV/chip card transaction. - pub tag: Option<String>, + pub tag: Option<Secret<String>>, /// Data from magnetic stripe of a card - pub track: Option<String>, + pub track: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] @@ -358,7 +358,7 @@ pub struct DigitalWallet { #[derive(Debug, Serialize, Deserialize)] pub struct Encryption { /// The encryption info used when sending encrypted card data to Global Payments. - pub info: Option<String>, + pub info: Option<Secret<String>>, /// The encryption method used when sending encrypted card data to Global Payments. pub method: Option<Method>, /// The version of encryption being used. diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs index 201297c399e..7d5efadaff8 100644 --- a/crates/router/src/connector/globalpay/response.rs +++ b/crates/router/src/connector/globalpay/response.rs @@ -6,9 +6,9 @@ use super::requests; #[derive(Debug, Serialize, Deserialize)] pub struct GlobalpayPaymentsResponse { /// A unique identifier for the merchant account set by Global Payments. - pub account_id: Option<String>, + pub account_id: Option<Secret<String>>, /// A meaningful label for the merchant account set by Global Payments. - pub account_name: Option<String>, + pub account_name: Option<Secret<String>>, /// Information about the Action executed. pub action: Option<Action>, /// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always @@ -37,7 +37,7 @@ pub struct GlobalpayPaymentsResponse { /// A unique identifier for the merchant set by Global Payments. pub merchant_id: Option<String>, /// A meaningful label for the merchant set by Global Payments. - pub merchant_name: Option<String>, + pub merchant_name: Option<Secret<String>>, pub payment_method: Option<PaymentMethod>, /// Merchant defined field to reference the transaction. pub reference: Option<String>, @@ -55,12 +55,12 @@ pub struct GlobalpayPaymentsResponse { #[derive(Debug, Serialize, Deserialize)] pub struct Action { /// The id of the app that was used to create the token. - pub app_id: Option<String>, + pub app_id: Option<Secret<String>>, /// The name of the app the user gave to the application. - pub app_name: Option<String>, + pub app_name: Option<Secret<String>>, /// A unique identifier for the object created by Global Payments. The first 3 characters /// identifies the resource an id relates to. - pub id: Option<String>, + pub id: Option<Secret<String>>, /// The result of the action executed. pub result_code: Option<ResultCode>, /// Global Payments time indicating when the object was created in ISO-8601 format. @@ -117,7 +117,7 @@ pub struct PaymentMethod { /// for that merchant. If the payment method is seen again this same value is generated. For /// cards the primary account number is checked only. The expiry date or the CVV is not used /// for this check. - pub fingerprint: Option<String>, + pub fingerprint: Option<Secret<String>>, /// If enabled, this field indicates whether the payment method has been seen before or is /// new. /// * EXISTS - Indicates that the payment method was seen on the platform before by this @@ -128,7 +128,7 @@ pub struct PaymentMethod { /// Unique Global Payments generated id used to reference a stored payment method on the /// Global Payments system. Often referred to as the payment method token. This value can be /// used instead of payment method details such as a card number and expiry date. - pub id: Option<String>, + pub id: Option<Secret<String>>, /// Result message from the payment method provider corresponding to the result code. pub message: Option<String>, /// Result code from the payment method provider. @@ -148,7 +148,7 @@ pub struct Apm { /// transaction. pub provider: Option<ApmProvider>, /// A name of the payer from the payment method system. - pub provider_payer_name: Option<String>, + pub provider_payer_name: Option<Secret<String>>, /// The time the payment method provider created the transaction at on their system. pub provider_time_created: Option<String>, /// The reference the payment method provider created for the transaction. @@ -162,28 +162,28 @@ pub struct Apm { pub redirect_url: Option<String>, /// A string generated by the payment method to represent the session created on the payment /// method's platform to facilitate the creation of a transaction. - pub session_token: Option<String>, + pub session_token: Option<Secret<String>>, pub payment_description: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct Bank { /// The local identifier of the bank account. - pub account_number: Option<String>, + pub account_number: Option<Secret<String>>, /// The local identifier of the bank. - pub code: Option<String>, + pub code: Option<Secret<String>>, /// The international identifier of the bank account. - pub iban: Option<String>, + pub iban: Option<Secret<String>>, /// The international identifier code for the bank. - pub identifier_code: Option<String>, + pub identifier_code: Option<Secret<String>>, /// The name associated with the bank account - pub name: Option<String>, + pub name: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct Mandate { /// The reference to identify the mandate. - pub code: Option<String>, + pub code: Option<Secret<String>>, } /// Information outlining the degree of authentication executed related to a transaction. @@ -205,7 +205,7 @@ pub struct BankTransfer { /// The last 4 characters of the local reference for a bank account number. pub masked_number_last4: Option<String>, /// The name of the bank. - pub name: Option<String>, + pub name: Option<Secret<String>>, /// The type of bank account associated with the payer's bank account. pub number_type: Option<NumberType>, } @@ -213,7 +213,7 @@ pub struct BankTransfer { #[derive(Debug, Serialize, Deserialize)] pub struct Card { /// Code generated when the card is successfully authorized. - pub authcode: Option<String>, + pub authcode: Option<Secret<String>>, /// The recommended AVS action to be taken by the agent processing the card transaction. pub avs_action: Option<String>, /// The result of the AVS address check. @@ -223,7 +223,7 @@ pub struct Card { /// Indicates the card brand that issued the card. pub brand: Option<Brand>, /// The unique reference created by the brands/schemes to uniquely identify the transaction. - pub brand_reference: Option<String>, + pub brand_reference: Option<Secret<String>>, /// The time returned by the card brand indicating when the transaction was processed on /// their system. pub brand_time_reference: Option<String>, @@ -235,7 +235,7 @@ pub struct Card { pub provider: Option<ProviderClass>, /// The card EMV tag response data from the card issuer for a contactless or chip card /// transaction. - pub tag_response: Option<String>, + pub tag_response: Option<Secret<String>>, } /// The result codes directly from the card issuer. diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 3124501bd6e..1e410946251 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -1,6 +1,6 @@ use common_utils::crypto::{self, GenerateDigest}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use rand::distributions::DistString; use serde::{Deserialize, Serialize}; use url::Url; @@ -164,8 +164,8 @@ impl TryFrom<&types::RefreshTokenRouterData> for GlobalpayRefreshTokenRequest { Ok(Self { app_id: globalpay_auth.app_id, - nonce, - secret, + nonce: Secret::new(nonce), + secret: Secret::new(secret), grant_type: "client_credentials".to_string(), }) } @@ -215,7 +215,7 @@ fn get_payment_response( .as_ref() .and_then(|card| card.brand_reference.to_owned()) .map(|id| types::MandateReference { - connector_mandate_id: Some(id), + connector_mandate_id: Some(id.expose()), payment_method_id: None, }) });
2024-02-27T07:49:58Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Globalpay. ## Test Case 1.a. Card Mandate Payment Create ``` { "amount": 10000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://hs-payments-test.netlify.app/payments", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4917 6100 0000 0000", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Joseph Doe", "card_cvc": "737" } }, "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } } , "mandate_type": { "multi_use": { "amount": 799, "currency": "USD" } } } } ``` 1.b. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response - Card Mandate Payment ``` "{\\\"account_id\\\":\\\"*** alloc::string::String ***\\\",\\\"account_name\\\":\\\"*** alloc::string::String ***\\\",\\\"action\\\":{\\\"app_id\\\":\\\"*** alloc::string::String ***\\\",\\\"app_name\\\":\\\"*** alloc::string::String ***\\\",\\\"id\\\":\\\"*** alloc::string::String ***\\\",\\\"result_code\\\":\\\"SUCCESS\\\",\\\"time_created\\\":\\\"2024-02-27T08:01:06.335Z\\\",\\\"type\\\":\\\"AUTHORIZE\\\"},\\\"amount\\\":\\\"10000\\\",\\\"authorization_mode\\\":null,\\\"batch_id\\\":\\\"BAT_1361216\\\",\\\"capture_mode\\\":\\\"AUTO\\\",\\\"channel\\\":\\\"CNP\\\",\\\"country\\\":\\\"US\\\",\\\"currency\\\":\\\"USD\\\",\\\"currency_conversion\\\":{\\\"id\\\":null},\\\"id\\\":\\\"TRN_QkEUmx4RVM2KJuIh1w97WKMkIQVOpg_44PMyDl6oy_1\\\",\\\"merchant_id\\\":\\\"MER_7e3e2c7df34f42819b3edee31022ee3f\\\",\\\"merchant_name\\\":\\\"*** alloc::string::String ***\\\",\\\"payment_method\\\":{\\\"apm\\\":null,\\\"authentication\\\":{\\\"three_ds\\\":null},\\\"bank_transfer\\\":null,\\\"card\\\":{\\\"authcode\\\":\\\"*** alloc::string::String ***\\\",\\\"avs_action\\\":\\\"\\\",\\\"avs_address_result\\\":\\\"NOT_CHECKED\\\",\\\"avs_postal_code_result\\\":\\\"NOT_CHECKED\\\",\\\"brand\\\":\\\"VISA\\\",\\\"brand_reference\\\":\\\"*** alloc::string::String ***\\\",\\\"brand_time_reference\\\":null,\\\"cvv_result\\\":\\\"NOT_CHECKED\\\",\\\"masked_number_last4\\\":\\\"*** alloc::string::String ***\\\",\\\"provider\\\":{\\\"card.provider.avs_address_result\\\":null,\\\"card.provider.avs_postal_code_result\\\":null,\\\"card.provider.avs_result\\\":null,\\\"card.provider.cvv_result\\\":null,\\\"card.provider.result\\\":null},\\\"tag_response\\\":\\\"*** alloc::string::String ***\\\"},\\\"digital_wallet\\\":null,\\\"entry_mode\\\":\\\"ECOM\\\",\\\"fingerprint\\\":null,\\\"fingerprint_presence_indicator\\\":null,\\\"id\\\":null,\\\"message\\\":\\\"[ test system ] Authorised\\\",\\\"result\\\":\\\"00\\\"},\\\"reference\\\":\\\"pay_zaVdoNy0DL44PMyDl6oy_1\\\",\\\"status\\\":\\\"CAPTURED\\\",\\\"time_created\\\":\\\"2024-02-27T08:01:06.335Z\\\",\\\"type\\\":\\\"SALE\\\"} ``` _Note: A know bug in recurring mandate payments_
2b0fbc70749338d5c501bbb782d6fc4747890d61
[ "crates/router/src/connector/globalpay/requests.rs", "crates/router/src/connector/globalpay/response.rs", "crates/router/src/connector/globalpay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3836
Bug: feat: change list roles, get role, info api to respond with groups
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index f19ff95f9ed..f46c5cf312b 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,15 +2,15 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ - CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, UpdateRoleRequest, + CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, + RoleInfoWithPermissionsResponse, UpdateRoleRequest, }, AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( - ListRolesResponse, - RoleInfoResponse, + RoleInfoWithPermissionsResponse, GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, @@ -18,5 +18,7 @@ common_utils::impl_misc_api_event_type!( DeleteUserRoleRequest, TransferOrgOwnershipRequest, CreateRoleRequest, - UpdateRoleRequest + UpdateRoleRequest, + ListRolesResponse, + RoleInfoResponse ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index ed0838adc24..80d3861969a 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,4 @@ +use common_enums::PermissionGroup; use common_utils::pii; use crate::user::DashboardEntryResponse; @@ -51,7 +52,14 @@ pub enum PermissionModule { } #[derive(Debug, serde::Serialize)] -pub struct AuthorizationInfoResponse(pub Vec<ModuleInfo>); +pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); + +#[derive(Debug, serde::Serialize)] +#[serde(untagged)] +pub enum AuthorizationInfo { + Module(ModuleInfo), + Group(GroupInfo), +} #[derive(Debug, serde::Serialize)] pub struct ModuleInfo { @@ -60,6 +68,13 @@ pub struct ModuleInfo { pub permissions: Vec<PermissionInfo>, } +#[derive(Debug, serde::Serialize)] +pub struct GroupInfo { + pub group: PermissionGroup, + pub description: &'static str, + pub permissions: Vec<PermissionInfo>, +} + #[derive(Debug, serde::Serialize)] pub struct PermissionInfo { pub enum_name: Permission, diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 4a767cfa723..fafb8fede0b 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -1,5 +1,7 @@ use common_enums::{PermissionGroup, RoleScope}; +use super::Permission; + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleRequest { pub role_name: String, @@ -16,10 +18,30 @@ pub struct UpdateRoleRequest { #[derive(Debug, serde::Serialize)] pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); +#[derive(Debug, serde::Deserialize)] +pub struct GetGroupsQueryParam { + pub groups: Option<bool>, +} + #[derive(Debug, serde::Serialize)] -pub struct RoleInfoResponse { +#[serde(untagged)] +pub enum RoleInfoResponse { + Permissions(RoleInfoWithPermissionsResponse), + Groups(RoleInfoWithGroupsResponse), +} + +#[derive(Debug, serde::Serialize)] +pub struct RoleInfoWithPermissionsResponse { pub role_id: String, - pub permissions: Vec<super::Permission>, + pub permissions: Vec<Permission>, + pub role_name: String, + pub role_scope: RoleScope, +} + +#[derive(Debug, serde::Serialize)] +pub struct RoleInfoWithGroupsResponse { + pub role_id: String, + pub groups: Vec<PermissionGroup>, pub role_name: String, pub role_scope: RoleScope, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b8168fc5329..4a87d0c256f 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2197,6 +2197,7 @@ pub enum RoleScope { serde::Deserialize, strum::Display, strum::EnumString, + strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b38faa34554..b8b8cbd24c7 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -442,7 +442,7 @@ pub async fn invite_user( .into()); } - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, &request.role_id, &user_from_token.merchant_id, @@ -659,7 +659,7 @@ async fn handle_invitation( .into()); } - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( state, &request.role_id, &user_from_token.merchant_id, @@ -1054,7 +1054,7 @@ pub async fn switch_merchant_id( let user = user_from_token.get_user_from_db(&state).await?; - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -1207,7 +1207,7 @@ pub async fn get_users_for_merchant_account( let users_user_roles_and_roles = futures::future::try_join_all(users_and_user_roles.into_iter().map( |(user, user_role)| async { - roles::get_role_info_from_role_id( + roles::RoleInfo::from_role_id( &state, &user_role.role_id, &user_role.merchant_id, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b954e0df6c6..9dca9b43d96 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -19,14 +19,28 @@ use crate::{ pub mod role; -pub async fn get_authorization_info( +// TODO: To be deprecated once groups are stable +pub async fn get_authorization_info_with_modules( _state: AppState, ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { Ok(ApplicationResponse::Json( user_role_api::AuthorizationInfoResponse( - info::get_authorization_info() + info::get_module_authorization_info() .into_iter() - .map(Into::into) + .map(|module_info| user_role_api::AuthorizationInfo::Module(module_info.into())) + .collect(), + ), + )) +} + +pub async fn get_authorization_info_with_groups( + _state: AppState, +) -> UserResponse<user_role_api::AuthorizationInfoResponse> { + Ok(ApplicationResponse::Json( + user_role_api::AuthorizationInfoResponse( + info::get_group_authorization_info() + .into_iter() + .map(user_role_api::AuthorizationInfo::Group) .collect(), ), )) @@ -37,7 +51,7 @@ pub async fn update_user_role( user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, ) -> UserResponse<()> { - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, &req.role_id, &user_from_token.merchant_id, @@ -67,7 +81,7 @@ pub async fn update_user_role( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - let role_to_be_updated = roles::get_role_info_from_role_id( + let role_to_be_updated = roles::RoleInfo::from_role_id( &state, &user_role_to_be_updated.role_id, &user_from_token.merchant_id, @@ -236,7 +250,7 @@ pub async fn delete_user_role( .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) { Some(user_role) => { - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, &user_role.role_id, &user_from_token.merchant_id, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 6edbda85bfd..cc31798bd8b 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -86,22 +86,25 @@ pub async fn create_role( Ok(ApplicationResponse::StatusOk) } -pub async fn list_invitable_roles( +// TODO: To be deprecated once groups are stable +pub async fn list_invitable_roles_with_permissions( state: AppState, 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::RoleInfoResponse { - permissions: role_info - .get_permissions_set() - .into_iter() - .map(Into::into) - .collect(), - role_id: role_id.to_string(), - role_name: role_info.get_role_name().to_string(), - role_scope: role_info.get_scope(), + .map(|(role_id, role_info)| { + role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse { + permissions: role_info + .get_permissions_set() + .into_iter() + .map(Into::into) + .collect(), + 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 @@ -110,17 +113,22 @@ pub async fn list_invitable_roles( .await .change_context(UserErrors::InternalServerError)? .into_iter() - .map(roles::RoleInfo::from) - .filter(|role_info| role_info.is_invitable()) - .map(|role_info| role_api::RoleInfoResponse { - permissions: role_info - .get_permissions_set() - .into_iter() - .map(Into::into) - .collect(), - role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), - role_scope: role_info.get_scope(), + .filter_map(|role| { + let role_info = roles::RoleInfo::from(role); + role_info + .is_invitable() + .then_some(role_api::RoleInfoResponse::Permissions( + role_api::RoleInfoWithPermissionsResponse { + permissions: role_info + .get_permissions_set() + .into_iter() + .map(Into::into) + .collect(), + 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( @@ -128,12 +136,54 @@ pub async fn list_invitable_roles( ))) } -pub async fn get_role( +pub async fn list_invitable_roles_with_groups( + state: AppState, + 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::RoleInfoResponse::Groups(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::RoleInfoResponse::Groups( + 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(), + ))) +} + +// TODO: To be deprecated once groups are stable +pub async fn get_role_with_permissions( state: AppState, user_from_token: UserFromToken, role: role_api::GetRoleRequest, ) -> UserResponse<role_api::RoleInfoResponse> { - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, &role.role_id, &user_from_token.merchant_id, @@ -152,12 +202,42 @@ pub async fn get_role( .map(Into::into) .collect(); - Ok(ApplicationResponse::Json(role_api::RoleInfoResponse { - permissions, - role_id: role.role_id, - role_name: role_info.get_role_name().to_string(), - role_scope: role_info.get_scope(), - })) + Ok(ApplicationResponse::Json( + role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse { + permissions, + role_id: role.role_id, + role_name: role_info.get_role_name().to_string(), + role_scope: role_info.get_scope(), + }), + )) +} + +pub async fn get_role_with_groups( + state: AppState, + user_from_token: UserFromToken, + role: role_api::GetRoleRequest, +) -> UserResponse<role_api::RoleInfoResponse> { + let role_info = roles::RoleInfo::from_role_id( + &state, + &role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if role_info.is_internal() { + return Err(UserErrors::InvalidRoleId.into()); + } + + Ok(ApplicationResponse::Json( + role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse { + groups: role_info.get_permission_groups().to_vec(), + role_id: role.role_id, + role_name: role_info.get_role_name().to_string(), + role_scope: role_info.get_scope(), + }), + )) } pub async fn update_role( @@ -182,7 +262,7 @@ pub async fn update_role( .await?; } - let role_info = roles::get_role_info_from_role_id( + let role_info = roles::RoleInfo::from_role_id( &state, role_id, &user_from_token.merchant_id, diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 52e739c36e1..75de9e7e6f7 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -1,10 +1,13 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use api_models::user_role as user_role_api; +use api_models::user_role::{self as user_role_api, role as role_api}; use router_env::Flow; use super::AppState; use crate::{ - core::{api_locking, user_role as user_role_core}, + core::{ + api_locking, + user_role::{self as user_role_core, role as role_core}, + }, services::{ api, authentication::{self as auth}, @@ -15,14 +18,23 @@ use crate::{ pub async fn get_authorization_info( state: web::Data<AppState>, http_req: HttpRequest, + query: web::Query<role_api::GetGroupsQueryParam>, ) -> HttpResponse { let flow = Flow::GetAuthorizationInfo; + let respond_with_groups = query.into_inner().groups.unwrap_or(false); Box::pin(api::server_wrap( flow, state.clone(), &http_req, (), - |state, _: (), _| user_role_core::get_authorization_info(state), + |state, _: (), _| async move { + // TODO: Permissions to be deprecated once groups are stable + if respond_with_groups { + user_role_core::get_authorization_info_with_groups(state).await + } else { + user_role_core::get_authorization_info_with_modules(state).await + } + }, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -36,7 +48,7 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) - state.clone(), &req, (), - |state, user, _| user_role_core::role::get_role_from_token(state, user), + |state, user, _| role_core::get_role_from_token(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -46,7 +58,7 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) - pub async fn create_role( state: web::Data<AppState>, req: HttpRequest, - json_payload: web::Json<user_role_api::role::CreateRoleRequest>, + json_payload: web::Json<role_api::CreateRoleRequest>, ) -> HttpResponse { let flow = Flow::CreateRole; Box::pin(api::server_wrap( @@ -54,21 +66,33 @@ pub async fn create_role( state.clone(), &req, json_payload.into_inner(), - user_role_core::role::create_role, + role_core::create_role, &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) .await } -pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn list_all_roles( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<role_api::GetGroupsQueryParam>, +) -> HttpResponse { let flow = Flow::ListRoles; + let respond_with_groups = query.into_inner().groups.unwrap_or(false); Box::pin(api::server_wrap( flow, state.clone(), &req, (), - |state, user, _| user_role_core::role::list_invitable_roles(state, user), + |state, user, _| async move { + // TODO: Permissions to be deprecated once groups are stable + if respond_with_groups { + role_core::list_invitable_roles_with_groups(state, user).await + } else { + role_core::list_invitable_roles_with_permissions(state, user).await + } + }, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -79,17 +103,26 @@ pub async fn get_role( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, + query: web::Query<role_api::GetGroupsQueryParam>, ) -> HttpResponse { let flow = Flow::GetRole; let request_payload = user_role_api::role::GetRoleRequest { role_id: path.into_inner(), }; + let respond_with_groups = query.into_inner().groups.unwrap_or(false); Box::pin(api::server_wrap( flow, state.clone(), &req, request_payload, - user_role_core::role::get_role, + |state, user, payload| async move { + // TODO: Permissions to be deprecated once groups are stable + if respond_with_groups { + role_core::get_role_with_groups(state, user, payload).await + } else { + role_core::get_role_with_permissions(state, user, payload).await + } + }, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -99,7 +132,7 @@ pub async fn get_role( pub async fn update_role( state: web::Data<AppState>, req: HttpRequest, - json_payload: web::Json<user_role_api::role::UpdateRoleRequest>, + json_payload: web::Json<role_api::UpdateRoleRequest>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::UpdateRole; @@ -110,7 +143,7 @@ pub async fn update_role( state.clone(), &req, json_payload.into_inner(), - |state, user, req| user_role_core::role::update_role(state, user, req, &role_id), + |state, user, req| role_core::update_role(state, user, req, &role_id), &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 034773a07ea..2a516cc82d5 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -6,6 +6,7 @@ use crate::{ routes::app::AppStateInfo, }; +#[cfg(feature = "olap")] pub mod info; pub mod permission_groups; pub mod permissions; diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index d982317e023..d6a20b7f8ed 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -1,30 +1,32 @@ +use api_models::user_role::{GroupInfo, PermissionInfo}; +use common_enums::PermissionGroup; use strum::{EnumIter, IntoEnumIterator}; -use super::permissions::Permission; +use super::{permission_groups::get_permissions_vec, permissions::Permission}; -pub fn get_authorization_info() -> Vec<ModuleInfo> { +pub fn get_module_authorization_info() -> Vec<ModuleInfo> { PermissionModule::iter() .map(|module| ModuleInfo::new(&module)) .collect() } -pub struct PermissionInfo { - pub enum_name: Permission, - pub description: &'static str, +pub fn get_group_authorization_info() -> Vec<GroupInfo> { + PermissionGroup::iter() + .map(get_group_info_from_permission_group) + .collect() } -impl PermissionInfo { - pub fn new(permissions: &[Permission]) -> Vec<Self> { - permissions - .iter() - .map(|&per| Self { - description: Permission::get_permission_description(&per), - enum_name: per, - }) - .collect() - } +pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> { + permissions + .iter() + .map(|&per| PermissionInfo { + description: Permission::get_permission_description(&per), + enum_name: per.into(), + }) + .collect() } +// TODO: Deprecate once groups are stable #[derive(PartialEq, EnumIter, Clone)] pub enum PermissionModule { Payments, @@ -60,6 +62,7 @@ impl PermissionModule { } } +// TODO: Deprecate once groups are stable pub struct ModuleInfo { pub module: PermissionModule, pub description: &'static str, @@ -75,7 +78,7 @@ impl ModuleInfo { PermissionModule::Payments => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::PaymentRead, Permission::PaymentWrite, ]), @@ -83,7 +86,7 @@ impl ModuleInfo { PermissionModule::Refunds => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::RefundRead, Permission::RefundWrite, ]), @@ -91,7 +94,7 @@ impl ModuleInfo { PermissionModule::MerchantAccount => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::MerchantAccountRead, Permission::MerchantAccountWrite, ]), @@ -99,7 +102,7 @@ impl ModuleInfo { PermissionModule::Connectors => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::MerchantConnectorAccountRead, Permission::MerchantConnectorAccountWrite, ]), @@ -107,7 +110,7 @@ impl ModuleInfo { PermissionModule::Routing => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::RoutingRead, Permission::RoutingWrite, ]), @@ -115,12 +118,12 @@ impl ModuleInfo { PermissionModule::Analytics => Self { module: module_name, description, - permissions: PermissionInfo::new(&[Permission::Analytics]), + permissions: get_permission_info_from_permissions(&[Permission::Analytics]), }, PermissionModule::Mandates => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::MandateRead, Permission::MandateWrite, ]), @@ -128,7 +131,7 @@ impl ModuleInfo { PermissionModule::Customer => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::CustomerRead, Permission::CustomerWrite, ]), @@ -136,7 +139,7 @@ impl ModuleInfo { PermissionModule::Disputes => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::DisputeRead, Permission::DisputeWrite, ]), @@ -144,7 +147,7 @@ impl ModuleInfo { PermissionModule::ThreeDsDecisionManager => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::ThreeDsDecisionManagerRead, Permission::ThreeDsDecisionManagerWrite, ]), @@ -153,7 +156,7 @@ impl ModuleInfo { PermissionModule::SurchargeDecisionManager => Self { module: module_name, description, - permissions: PermissionInfo::new(&[ + permissions: get_permission_info_from_permissions(&[ Permission::SurchargeDecisionManagerRead, Permission::SurchargeDecisionManagerWrite, ]), @@ -161,8 +164,46 @@ impl ModuleInfo { PermissionModule::AccountCreate => Self { module: module_name, description, - permissions: PermissionInfo::new(&[Permission::MerchantAccountCreate]), + permissions: get_permission_info_from_permissions(&[ + Permission::MerchantAccountCreate, + ]), }, } } } + +fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo { + let description = get_group_description(group); + GroupInfo { + group, + description, + permissions: get_permission_info_from_permissions(get_permissions_vec(&group)), + } +} + +fn get_group_description(group: PermissionGroup) -> &'static str { + match group { + PermissionGroup::OperationsView => { + "View Payments, Refunds, Mandates, Disputes and Customers" + } + PermissionGroup::OperationsManage => { + "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers" + } + PermissionGroup::ConnectorsView => { + "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details" + } + PermissionGroup::ConnectorsManage => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager", + PermissionGroup::WorkflowsView => { + "View Routing, 3DS Decision Manager, Surcharge Decision Manager" + } + PermissionGroup::WorkflowsManage => { + "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager" + } + PermissionGroup::AnalyticsView => "View Analytics", + PermissionGroup::UsersView => "View Users", + PermissionGroup::UsersManage => "Manage and invite Users to the Team", + PermissionGroup::MerchantDetailsView => "View Merchant Details", + PermissionGroup::MerchantDetailsManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc", + PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", + } +} diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index 6372799f98c..f99892c565d 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -65,22 +65,22 @@ impl RoleInfo { .iter() .any(|group| get_permissions_vec(group).contains(required_permission)) } -} -pub async fn get_role_info_from_role_id( - state: &AppState, - role_id: &str, - merchant_id: &str, - org_id: &str, -) -> CustomResult<RoleInfo, errors::StorageError> { - if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { - Ok(role.clone()) - } else { - state - .store - .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) - .await - .map(RoleInfo::from) + pub async fn from_role_id( + state: &AppState, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<Self, errors::StorageError> { + if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { + Ok(role.clone()) + } else { + state + .store + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .await + .map(Self::from) + } } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index a759bf00806..d6e878456e8 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -811,15 +811,6 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule { } } -impl From<info::PermissionInfo> for user_role_api::PermissionInfo { - fn from(value: info::PermissionInfo) -> Self { - Self { - enum_name: value.enum_name.into(), - description: value.description, - } - } -} - pub enum SignInWithRoleStrategyType { SingleRole(SignInWithSingleRoleStrategy), MultipleRoles(SignInWithMultipleRolesStrategy), diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index e9b7143a26e..c3b795d1a57 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -64,7 +64,7 @@ impl UserFromToken { } pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> { - roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) + roles::RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) .await .change_context(UserErrors::InternalServerError) }
2024-02-27T07:21:21Z
## Description <!-- Describe your changes in detail --> Change `list_roles`, `get_role` and `get_authorization_info` api to respond with groups if asked. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #3836 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> All the following APIs have a query param called groups, setting it to true will return the following response. 1. Get role list ``` curl --location 'http://localhost:8080/user/role/list?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` [ { "role_id": "merchant_iam_admin", "groups": [ "operations_view", "analytics_view", "users_view", "users_manage", "merchant_details_view" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage" ], "role_name": "Admin", "role_scope": "organization" }, { "role_id": "merchant_developer", "groups": [ "operations_view", "connectors_view", "analytics_view", "users_view", "merchant_details_view", "merchant_details_manage" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_view_only", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_operator", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "role_01JlOAdLoUqtynjUfEV4", "groups": [ "users_view" ], "role_name": "custom_role", "role_scope": "merchant" } ] ``` 2. Get role info ``` curl --location 'http://localhost:8080/user/role/role_01JlOAdLoUqtynjUfEV4?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` { "role_id": "role_01JlOAdLoUqtynjUfEV4", "groups": [ "users_view" ], "role_name": "custom_role", "role_scope": "merchant" } ``` 3. Permission Info ``` curl --location 'http://localhost:8080/user/permission_info?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` [ { "group": "operations_view", "description": "View Payments, Refunds, Mandates, Disputes and Customers", "permissions": [ { "enum_name": "PaymentRead", "description": "View all payments" }, { "enum_name": "RefundRead", "description": "View all refunds" }, { "enum_name": "MandateRead", "description": "View mandates" }, { "enum_name": "DisputeRead", "description": "View disputes" }, { "enum_name": "CustomerRead", "description": "View customers" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "operations_manage", "description": "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers", "permissions": [ { "enum_name": "PaymentWrite", "description": "Create payment, download payments data" }, { "enum_name": "RefundWrite", "description": "Create refund, download refunds data" }, { "enum_name": "MandateWrite", "description": "Create and update mandates" }, { "enum_name": "DisputeWrite", "description": "Create and update disputes" }, { "enum_name": "CustomerWrite", "description": "Create, update and delete customers" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "connectors_view", "description": "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details", "permissions": [ { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "connectors_manage", "description": "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager", "permissions": [ { "enum_name": "MerchantConnectorAccountWrite", "description": "Create, update, verify and delete connector configurations" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "workflows_view", "description": "View Routing, 3DS Decision Manager, Surcharge Decision Manager", "permissions": [ { "enum_name": "RoutingRead", "description": "View routing configuration" }, { "enum_name": "ThreeDsDecisionManagerRead", "description": "View all 3DS decision rules configured for a merchant" }, { "enum_name": "SurchargeDecisionManagerRead", "description": "View all the surcharge decision rules" }, { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "workflows_manage", "description": "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager", "permissions": [ { "enum_name": "RoutingWrite", "description": "Create and activate routing configurations" }, { "enum_name": "ThreeDsDecisionManagerWrite", "description": "Create and update 3DS decision rules" }, { "enum_name": "SurchargeDecisionManagerWrite", "description": "Create and update the surcharge decision rules" }, { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "analytics_view", "description": "View Analytics", "permissions": [ { "enum_name": "Analytics", "description": "Access to analytics module" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "users_view", "description": "View Users", "permissions": [ { "enum_name": "UsersRead", "description": "View all the users for a merchant" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "users_manage", "description": "Manage and invite Users to the Team", "permissions": [ { "enum_name": "UsersWrite", "description": "Invite users, assign and update roles" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "merchant_details_view", "description": "View Merchant Details", "permissions": [ { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "merchant_details_manage", "description": "Create, modify and delete Merchant Details like api keys, webhooks, etc", "permissions": [ { "enum_name": "MerchantAccountWrite", "description": "Update merchant account details, configure webhooks, manage api keys" }, { "enum_name": "ApiKeyRead", "description": "View API keys (masked generated for the system" }, { "enum_name": "ApiKeyWrite", "description": "Create and update API keys" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "organization_manage", "description": "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", "permissions": [ { "enum_name": "MerchantAccountCreate", "description": "Create merchant account" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] } ] ```
1c6913be747bd3da53fa2b48e339810bb30226e7
All the following APIs have a query param called groups, setting it to true will return the following response. 1. Get role list ``` curl --location 'http://localhost:8080/user/role/list?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` [ { "role_id": "merchant_iam_admin", "groups": [ "operations_view", "analytics_view", "users_view", "users_manage", "merchant_details_view" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage" ], "role_name": "Admin", "role_scope": "organization" }, { "role_id": "merchant_developer", "groups": [ "operations_view", "connectors_view", "analytics_view", "users_view", "merchant_details_view", "merchant_details_manage" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_view_only", "groups": [ "operations_view", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_operator", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "role_01JlOAdLoUqtynjUfEV4", "groups": [ "users_view" ], "role_name": "custom_role", "role_scope": "merchant" } ] ``` 2. Get role info ``` curl --location 'http://localhost:8080/user/role/role_01JlOAdLoUqtynjUfEV4?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` { "role_id": "role_01JlOAdLoUqtynjUfEV4", "groups": [ "users_view" ], "role_name": "custom_role", "role_scope": "merchant" } ``` 3. Permission Info ``` curl --location 'http://localhost:8080/user/permission_info?groups=true' \ --header 'Authorization: Bearer JWT' ``` Response ``` [ { "group": "operations_view", "description": "View Payments, Refunds, Mandates, Disputes and Customers", "permissions": [ { "enum_name": "PaymentRead", "description": "View all payments" }, { "enum_name": "RefundRead", "description": "View all refunds" }, { "enum_name": "MandateRead", "description": "View mandates" }, { "enum_name": "DisputeRead", "description": "View disputes" }, { "enum_name": "CustomerRead", "description": "View customers" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "operations_manage", "description": "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers", "permissions": [ { "enum_name": "PaymentWrite", "description": "Create payment, download payments data" }, { "enum_name": "RefundWrite", "description": "Create refund, download refunds data" }, { "enum_name": "MandateWrite", "description": "Create and update mandates" }, { "enum_name": "DisputeWrite", "description": "Create and update disputes" }, { "enum_name": "CustomerWrite", "description": "Create, update and delete customers" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "connectors_view", "description": "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details", "permissions": [ { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "connectors_manage", "description": "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager", "permissions": [ { "enum_name": "MerchantConnectorAccountWrite", "description": "Create, update, verify and delete connector configurations" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "workflows_view", "description": "View Routing, 3DS Decision Manager, Surcharge Decision Manager", "permissions": [ { "enum_name": "RoutingRead", "description": "View routing configuration" }, { "enum_name": "ThreeDsDecisionManagerRead", "description": "View all 3DS decision rules configured for a merchant" }, { "enum_name": "SurchargeDecisionManagerRead", "description": "View all the surcharge decision rules" }, { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "workflows_manage", "description": "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager", "permissions": [ { "enum_name": "RoutingWrite", "description": "Create and activate routing configurations" }, { "enum_name": "ThreeDsDecisionManagerWrite", "description": "Create and update 3DS decision rules" }, { "enum_name": "SurchargeDecisionManagerWrite", "description": "Create and update the surcharge decision rules" }, { "enum_name": "MerchantConnectorAccountRead", "description": "View connectors configured" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "analytics_view", "description": "View Analytics", "permissions": [ { "enum_name": "Analytics", "description": "Access to analytics module" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "users_view", "description": "View Users", "permissions": [ { "enum_name": "UsersRead", "description": "View all the users for a merchant" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "users_manage", "description": "Manage and invite Users to the Team", "permissions": [ { "enum_name": "UsersWrite", "description": "Invite users, assign and update roles" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "merchant_details_view", "description": "View Merchant Details", "permissions": [ { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "merchant_details_manage", "description": "Create, modify and delete Merchant Details like api keys, webhooks, etc", "permissions": [ { "enum_name": "MerchantAccountWrite", "description": "Update merchant account details, configure webhooks, manage api keys" }, { "enum_name": "ApiKeyRead", "description": "View API keys (masked generated for the system" }, { "enum_name": "ApiKeyWrite", "description": "Create and update API keys" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] }, { "group": "organization_manage", "description": "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", "permissions": [ { "enum_name": "MerchantAccountCreate", "description": "Create merchant account" }, { "enum_name": "MerchantAccountRead", "description": "View merchant account details" } ] } ] ```
[ "crates/api_models/src/events/user_role.rs", "crates/api_models/src/user_role.rs", "crates/api_models/src/user_role/role.rs", "crates/common_enums/src/enums.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/rout...
juspay/hyperswitch
juspay__hyperswitch-3833
Bug: [Bug] metadata validation for update payment connector Metadata validation in update payment connector happens even if we don't pass metadata in the request. Instead, if metadata is not present we should consider MCA metadata in update_payment_connector function .
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 2b87d64c6ac..14c88448125 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1185,6 +1185,7 @@ pub async fn update_payment_connector( field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; + let metadata = req.metadata.clone().or(mca.metadata.clone()); let connector_name = mca.connector_name.as_ref(); let connector_enum = api_models::enums::Connector::from_str(connector_name) .into_report() @@ -1192,27 +1193,27 @@ pub async fn update_payment_connector( field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; - validate_auth_and_metadata_type(connector_enum, &auth, &req.metadata).map_err( - |err| match *err.current_context() { - errors::ConnectorError::InvalidConnectorName => { - err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The connector name is invalid".to_string(), - }) - } - 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(), - }) - } - _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The request body is invalid".to_string(), + validate_auth_and_metadata_type(connector_enum, &auth, &metadata).map_err(|err| match *err + .current_context() + { + errors::ConnectorError::InvalidConnectorName => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The connector name is invalid".to_string(), + }) + } + 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(), + }) + } + _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The request body is invalid".to_string(), + }), + })?; let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
2024-02-27T05:55:52Z
## Description <!-- Describe your changes in detail --> Metadata validation in update payment connector happens even if we don't pass metadata in the request. This pr fixes metadata validation in update payment connector function. If metadata is not present we consider mca metadata. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Metadata validation in update payment connector happens even if we don't pass metadata in the request. This pr fixes metadata validation in update payment connector function. If metadata is not present we consider mca metadata. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Test case 1 :** step 1 : Create merchant connector account for Fiserv. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_Id>/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_name": "fiserv", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "API_KEY", "key1": "KEY1", "api_secret": "API_SECRET" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "terminal_id":"TERMINAL_ID" } }' ``` step 2 : Update merchant connector account without updating metadata, It should not throw 422. here below curl is updating connector webhook details. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_webhook_details": { "merchant_secret": "MERCHANT_SECRET", "additional_secret": null } }' ``` **Test case 2 :** step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1 step 2 : Pass valid metadata in update payment connector, This should update metadata. where valid metadata for fiserv is `{"terminal_id": "TERMINAL_ID"}` ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": {"terminal_id": "DIFFERENT_TERMINAL_ID"} }' ``` **Test case 3 :** step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1 step 2 : Pass Invalid metadata or empty metadata in update payment connector, This should throw error. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": {} }' ``` This can be done for any other connector which have metadata validation while creating merchant connector account(Braintree, Coinbase ).
2b0fbc70749338d5c501bbb782d6fc4747890d61
**Test case 1 :** step 1 : Create merchant connector account for Fiserv. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_Id>/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_name": "fiserv", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "API_KEY", "key1": "KEY1", "api_secret": "API_SECRET" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "terminal_id":"TERMINAL_ID" } }' ``` step 2 : Update merchant connector account without updating metadata, It should not throw 422. here below curl is updating connector webhook details. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_webhook_details": { "merchant_secret": "MERCHANT_SECRET", "additional_secret": null } }' ``` **Test case 2 :** step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1 step 2 : Pass valid metadata in update payment connector, This should update metadata. where valid metadata for fiserv is `{"terminal_id": "TERMINAL_ID"}` ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": {"terminal_id": "DIFFERENT_TERMINAL_ID"} }' ``` **Test case 3 :** step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1 step 2 : Pass Invalid metadata or empty metadata in update payment connector, This should throw error. ``` curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": {} }' ``` This can be done for any other connector which have metadata validation while creating merchant connector account(Braintree, Coinbase ).
[ "crates/router/src/core/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3792
Bug: [BUG] Nuvei payment declined errors are not captured ### Bug Description Nuvei Payments error are captured and handled only for transaction status : "Error" Testing [card declined](https://docs.nuvei.com/documentation/integration/testing/testing-cards/#cards-that-return-declined) is not responding with expected error code and message error_code and error_message is responded as null <img width="615" alt="image" src="https://github.com/juspay/hyperswitch/assets/97145230/220ba157-fb4f-4d79-bd51-74c19fbab0ca"> ### Expected Behavior Expected Response : ``` { "payment_id": "pay_99nCeujKAhTB27glC5Fw", "merchant_id": "mannar_1707830889", "status": "failed", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_99nCeujKAhTB27glC5Fw_secret_bTMbuN08o3fvjytYPyEd", "created": "2024-02-23T06:32:16.486Z", "currency": "USD", "customer_id": "futurebilling", "description": "testing", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 100, "currency": "USD", "start_date": null, "end_date": "2025-05-03T04:07:52.723Z", "metadata": { "frequency": "1" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4872", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400017", "card_extended_bin": "40001739", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": "token_EDEFLY9j7GRL5eFlIgoa", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "JP", "line1": "1467", "line2": "jkjj Street", "line3": "no 1111 Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "-1", "error_message": "Insufficient Funds", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "futurebilling", "created_at": 1708669936, "expires": 1708673536, "secret": "epk_8c2eac5c44034e18827f3010def0cda0" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_9dOQiOX8uDPqZLfv43Nk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Qy72oJr0qiR02QRfx5s", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-23T06:47:16.486Z", "fingerprint": null } ``` ### Actual Behavior Actual Response : ``` { "payment_id": "pay_3eyj9vgQYARPh25iJEXi", "merchant_id": "mannar_1707830889", "status": "failed", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_3eyj9vgQYARPh25iJEXi_secret_Rml2NqJ8c2ObpTHY8NPf", "created": "2024-02-23T06:28:38.195Z", "currency": "USD", "customer_id": "futurebilling", "description": "testing", "refunds": null, "disputes": null, "mandate_id": "man_1hH78HlOeGSfhqXwHoBw", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 100, "currency": "USD", "start_date": null, "end_date": "2025-05-03T04:07:52.723Z", "metadata": { "frequency": "1" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4872", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400017", "card_extended_bin": "40001739", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": "token_04lcgdDFWKc3j1FaI3Lu", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "JP", "line1": "1467", "line2": "jkjj Street", "line3": "no 1111 Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "futurebilling", "created_at": 1708669718, "expires": 1708673318, "secret": "epk_ae27cd98c8b64cc4845e6c1e0f3d84d9" }, "manual_retry_allowed": true, "connector_transaction_id": "711000000032512257", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "423006018", "payment_link": null, "profile_id": "pro_9dOQiOX8uDPqZLfv43Nk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Qy72oJr0qiR02QRfx5s", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-23T06:43:38.195Z", "fingerprint": null } ``` ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 13d522b86cc..bf622d7a077 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1360,7 +1360,7 @@ fn build_error_response<T>( http_code, )); match response.transaction_status { - Some(NuveiTransactionStatus::Error) => err, + Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match response .gw_error_reason .as_ref() diff --git a/postman/collection-dir/nuvei/.auth.json b/postman/collection-dir/nuvei/.auth.json new file mode 100644 index 00000000000..915a2835790 --- /dev/null +++ b/postman/collection-dir/nuvei/.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/nuvei/.event.meta.json b/postman/collection-dir/nuvei/.event.meta.json new file mode 100644 index 00000000000..2df9d47d936 --- /dev/null +++ b/postman/collection-dir/nuvei/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.prerequest.js", + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/.info.json b/postman/collection-dir/nuvei/.info.json new file mode 100644 index 00000000000..b1f71f3eee2 --- /dev/null +++ b/postman/collection-dir/nuvei/.info.json @@ -0,0 +1,9 @@ +{ + "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: [support@juspay.in](mailto:support@juspay.in)", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "19204656" + } +} diff --git a/postman/collection-dir/nuvei/.meta.json b/postman/collection-dir/nuvei/.meta.json new file mode 100644 index 00000000000..91b6a65c5bc --- /dev/null +++ b/postman/collection-dir/nuvei/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Health check", + "Flow Testcases" + ] +} diff --git a/postman/collection-dir/nuvei/.variable.json b/postman/collection-dir/nuvei/.variable.json new file mode 100644 index 00000000000..84482b418fb --- /dev/null +++ b/postman/collection-dir/nuvei/.variable.json @@ -0,0 +1,86 @@ +{ + "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" + } + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/.meta.json new file mode 100644 index 00000000000..78d8ddcf5bb --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "QuickStart", + "Variation Cases" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json new file mode 100644 index 00000000000..c4939d7ab91 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json @@ -0,0 +1,11 @@ +{ + "childrenOrder": [ + "Merchant Account - Create", + "API Key - Create", + "Payment Connector - Create", + "Payments - Create", + "Payments - Retrieve", + "Refunds - Create", + "Refunds - Retrieve" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/event.test.js new file mode 100644 index 00000000000..4e27c5a5025 --- /dev/null +++ b/postman/collection-dir/nuvei/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/nuvei/Flow Testcases/QuickStart/API Key - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/request.json new file mode 100644 index 00000000000..4e4c6628497 --- /dev/null +++ b/postman/collection-dir/nuvei/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": "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}}" + } + ] + } +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js new file mode 100644 index 00000000000..7de0d5beb31 --- /dev/null +++ b/postman/collection-dir/nuvei/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/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/request.json new file mode 100644 index 00000000000..ffeea3410a4 --- /dev/null +++ b/postman/collection-dir/nuvei/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", + "primary_business_details": [ + { + "country": "US", + "business": "default" + } + ], + "merchant_details": { + "primary_contact_person": "John Test", + "primary_email": "JohnTest@test.com", + "primary_phone": "sunt laborum", + "secondary_contact_person": "John Test2", + "secondary_email": "JohnTest2@test.com", + "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." +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js new file mode 100644 index 00000000000..88e92d8d84a --- /dev/null +++ b/postman/collection-dir/nuvei/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/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json new file mode 100644 index 00000000000..32e3afc6348 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -0,0 +1,98 @@ +{ + "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": "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." +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js new file mode 100644 index 00000000000..dc285fb1afe --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js @@ -0,0 +1,66 @@ +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.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json new file mode 100644 index 00000000000..9ca781cb8f8 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js new file mode 100644 index 00000000000..bbd8e544e2c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js @@ -0,0 +1,30 @@ +// 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.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/request.json new file mode 100644 index 00000000000..203cc8ad8d1 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/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 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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js new file mode 100644 index 00000000000..61f29c86540 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js @@ -0,0 +1,33 @@ +// 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.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json new file mode 100644 index 00000000000..e9cb375957e --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json @@ -0,0 +1,32 @@ +{ + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js new file mode 100644 index 00000000000..bbd8e544e2c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js @@ -0,0 +1,30 @@ +// 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.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json new file mode 100644 index 00000000000..06b44cf7fd3 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json @@ -0,0 +1,33 @@ +{ + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json new file mode 100644 index 00000000000..8ae4ccb0019 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Scenario1- Create Payment with Invalid card", + "Scenario1- Payment Decline scenario" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json new file mode 100644 index 00000000000..10f13eaa42a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json @@ -0,0 +1,7 @@ +{ + "childrenOrder": [ + "Payments - Create(Expired Card)", + "Payments - Create(Invalid CVV)", + "Payments - Create(Lost Card)" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js new file mode 100644 index 00000000000..f6232ceea45 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json new file mode 100644 index 00000000000..6bfc1515950 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js new file mode 100644 index 00000000000..4dee6c97027 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json new file mode 100644 index 00000000000..f936588a9f5 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js new file mode 100644 index 00000000000..c603c454610 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json new file mode 100644 index 00000000000..9d317ce5293 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json new file mode 100644 index 00000000000..c0cc1f23cc1 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json @@ -0,0 +1,7 @@ +{ + "childrenOrder": [ + "Payments - Create(Decline)", + "Payments - Create(Do Not Honor)", + "Payments - Create(Insufficient Funds)" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js new file mode 100644 index 00000000000..354776fa309 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json new file mode 100644 index 00000000000..93f6d30da08 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js new file mode 100644 index 00000000000..c2070d7a153 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json new file mode 100644 index 00000000000..b9cbf1fa7a5 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js new file mode 100644 index 00000000000..09d39c6965c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js @@ -0,0 +1,73 @@ +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"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json new file mode 100644 index 00000000000..41edc08e2f9 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json @@ -0,0 +1,111 @@ +{ + "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": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "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" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Health check/.meta.json b/postman/collection-dir/nuvei/Health check/.meta.json new file mode 100644 index 00000000000..66ee7e50cab --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "New Request" + ] +} diff --git a/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json b/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Health check/New Request/event.test.js b/postman/collection-dir/nuvei/Health check/New Request/event.test.js new file mode 100644 index 00000000000..b490b8be090 --- /dev/null +++ b/postman/collection-dir/nuvei/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/nuvei/Health check/New Request/request.json b/postman/collection-dir/nuvei/Health check/New Request/request.json new file mode 100644 index 00000000000..4cc8d4b1a96 --- /dev/null +++ b/postman/collection-dir/nuvei/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/nuvei/Health check/New Request/response.json b/postman/collection-dir/nuvei/Health check/New Request/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/event.prerequest.js b/postman/collection-dir/nuvei/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/event.test.js b/postman/collection-dir/nuvei/event.test.js new file mode 100644 index 00000000000..fb52caec30f --- /dev/null +++ b/postman/collection-dir/nuvei/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")); diff --git a/postman/collection-json/nuvei.postman_collection.json b/postman/collection-json/nuvei.postman_collection.json new file mode 100644 index 00000000000..4c6b80a3d5c --- /dev/null +++ b/postman/collection-json/nuvei.postman_collection.json @@ -0,0 +1,1662 @@ + +{ + "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: [support@juspay.in](mailto:support@juspay.in)", + "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\":\"JohnTest@test.com\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"JohnTest2@test.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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\":\"guest@example.com\",\"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
2024-02-27T04:51:25Z
## Description Nuvei error handling for payment declined status ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context https://github.com/juspay/hyperswitch/issues/3792 If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested via postman test and included scripts
901d61bc0ddb4b2ad742de927126f468629a79af
Tested via postman test and included scripts
[ "crates/router/src/connector/nuvei/transformers.rs", "postman/collection-dir/nuvei/.auth.json", "postman/collection-dir/nuvei/.event.meta.json", "postman/collection-dir/nuvei/.info.json", "postman/collection-dir/nuvei/.meta.json", "postman/collection-dir/nuvei/.variable.json", "postman/collection-dir/nu...
juspay/hyperswitch
juspay__hyperswitch-4030
Bug: [GlobalSearch] - API support for free form text search These would involve getting a string from the user & searching for that string in ES, using the msearch can be considered optional here. (don't build support for specific key/value or time range filters yet) + deployment build msearch API + separate index search API...
diff --git a/Cargo.lock b/Cargo.lock index 7c7b2b9a761..e3c39b71842 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -55,7 +55,7 @@ dependencies = [ "flate2", "futures-core", "h2", - "http", + "http 0.2.9", "httparse", "httpdate", "itoa", @@ -128,7 +128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799" dependencies = [ "bytestring", - "http", + "http 0.2.9", "regex", "serde", "tracing", @@ -183,10 +183,10 @@ dependencies = [ "actix-service", "actix-utils", "futures-core", - "http", + "http 0.2.9", "impl-more", "pin-project-lite", - "rustls 0.21.7", + "rustls 0.21.10", "rustls-webpki", "tokio 1.36.0", "tokio-rustls 0.23.4", @@ -229,7 +229,7 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "http", + "http 0.2.9", "itoa", "language-tags", "log", @@ -340,9 +340,9 @@ dependencies = [ "actix-web", "api_models", "async-trait", - "aws-config", + "aws-config 1.1.7", "aws-sdk-lambda", - "aws-smithy-types", + "aws-smithy-types 1.1.7", "bigdecimal", "common_utils", "diesel_models", @@ -352,6 +352,7 @@ dependencies = [ "hyperswitch_interfaces", "masking", "once_cell", + "opensearch", "reqwest", "router_env", "serde", @@ -621,7 +622,7 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.9", "itoa", "log", "mime", @@ -641,23 +642,23 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcdcf0d683fe9c23d32cf5b53c9918ea0a500375a9fb20109802552658e576c9" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-http", - "aws-sdk-sso", - "aws-sdk-sts", - "aws-smithy-async", + "aws-sdk-sso 0.28.0", + "aws-sdk-sts 0.28.0", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", "fastrand 1.9.0", "hex", - "http", + "http 0.2.9", "hyper", - "ring", + "ring 0.16.20", "time", "tokio 1.36.0", "tower", @@ -665,30 +666,72 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aws-config" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b96342ea8948ab9bef3e6234ea97fc32e2d8a88d8fb6a084e52267317f94b6b" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-runtime", + "aws-sdk-sso 1.15.0", + "aws-sdk-ssooidc", + "aws-sdk-sts 1.15.0", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-json 0.60.6", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-types 1.1.7", + "bytes 1.5.0", + "fastrand 2.0.1", + "hex", + "http 0.2.9", + "hyper", + "ring 0.17.8", + "time", + "tokio 1.36.0", + "tracing", + "zeroize", +] + [[package]] name = "aws-credential-types" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fcdb2f7acbc076ff5ad05e7864bdb191ca70a6fd07668dc3a1a8bcd051de5ae" dependencies = [ - "aws-smithy-async", - "aws-smithy-types", + "aws-smithy-async 0.55.3", + "aws-smithy-types 0.55.3", "fastrand 1.9.0", "tokio 1.36.0", "tracing", "zeroize", ] +[[package]] +name = "aws-credential-types" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "273fa47dafc9ef14c2c074ddddbea4561ff01b7f68d5091c0e9737ced605c01d" +dependencies = [ + "aws-smithy-async 1.1.7", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "zeroize", +] + [[package]] name = "aws-endpoint" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8cce1c41a6cfaa726adee9ebb9a56fcd2bbfd8be49fd8a04c5e20fd968330b04" dependencies = [ - "aws-smithy-http", - "aws-smithy-types", - "aws-types", - "http", + "aws-smithy-http 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", + "http 0.2.9", "regex", "tracing", ] @@ -699,12 +742,12 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aadbc44e7a8f3e71c8b374e03ecd972869eb91dd2bc89ed018954a52ba84bc44" dependencies = [ - "aws-credential-types", - "aws-smithy-http", - "aws-smithy-types", - "aws-types", + "aws-credential-types 0.55.3", + "aws-smithy-http 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "http-body", "lazy_static", "percent-encoding", @@ -712,25 +755,48 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-runtime" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e38bab716c8bf07da24be07ecc02e0f5656ce8f30a891322ecdcb202f943b85" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-sigv4 1.1.7", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-types 1.1.7", + "bytes 1.5.0", + "fastrand 2.0.1", + "http 0.2.9", + "http-body", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid", +] + [[package]] name = "aws-sdk-kms" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "545335abd7c6ef7285d2972a67b9f8279ff5fec8bbb3ffc637fa436ba1e6e434" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-endpoint", "aws-http", "aws-sig-auth", - "aws-smithy-async", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "regex", "tokio-stream", "tower", @@ -739,26 +805,23 @@ dependencies = [ [[package]] name = "aws-sdk-lambda" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ad176ffaa3aafa532246eb6a9f18a7d68da19950704ecc95d33d9dc3c62a9b" -dependencies = [ - "aws-credential-types", - "aws-endpoint", - "aws-http", - "aws-sig-auth", - "aws-smithy-async", - "aws-smithy-client", - "aws-smithy-http", - "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-types", +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4714bdfe1171542377f84c1034b1c64e3e7544119765f205402ae159b5b9b4" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-runtime", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-json 0.60.6", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-types 1.1.7", "bytes 1.5.0", - "http", - "regex", - "tokio-stream", - "tower", + "http 0.2.9", + "once_cell", + "regex-lite", "tracing", ] @@ -768,23 +831,23 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fba197193cbb4bcb6aad8d99796b2291f36fa89562ded5d4501363055b0de89f" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-endpoint", "aws-http", "aws-sig-auth", - "aws-sigv4", - "aws-smithy-async", + "aws-sigv4 0.55.3", + "aws-smithy-async 0.55.3", "aws-smithy-checksums", "aws-smithy-client", "aws-smithy-eventstream", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-types 0.55.3", + "aws-smithy-xml 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "http-body", "once_cell", "percent-encoding", @@ -801,19 +864,19 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4891169a246b580136f4d3682c11a68b710bdc1027dd7774023fa651a87f10b6" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-endpoint", "aws-http", "aws-sig-auth", - "aws-smithy-async", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "regex", "tokio-stream", "tower", @@ -826,63 +889,130 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8b812340d86d4a766b2ca73f740dfd47a97c2dff0c06c8517a16d88241957e4" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-endpoint", "aws-http", "aws-sig-auth", - "aws-smithy-async", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-types 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "regex", "tokio-stream", "tower", "tracing", ] +[[package]] +name = "aws-sdk-sso" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d84bd3925a17c9adbf6ec65d52104a44a09629d8f70290542beeee69a95aee7f" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-runtime", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-json 0.60.6", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-types 1.1.7", + "bytes 1.5.0", + "http 0.2.9", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssooidc" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c2dae39e997f58bc4d6292e6244b26ba630c01ab671b6f9f44309de3eb80ab8" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-runtime", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-json 0.60.6", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-types 1.1.7", + "bytes 1.5.0", + "http 0.2.9", + "once_cell", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-sts" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "265fac131fbfc188e5c3d96652ea90ecc676a934e3174eaaee523c6cec040b3b" dependencies = [ - "aws-credential-types", + "aws-credential-types 0.55.3", "aws-endpoint", "aws-http", "aws-sig-auth", - "aws-smithy-async", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-query", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", + "aws-smithy-json 0.55.3", + "aws-smithy-query 0.55.3", + "aws-smithy-types 0.55.3", + "aws-smithy-xml 0.55.3", + "aws-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "regex", "tower", "tracing", ] +[[package]] +name = "aws-sdk-sts" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17fd9a53869fee17cea77e352084e1aa71e2c5e323d974c13a9c2bcfd9544c7f" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-runtime", + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-json 0.60.6", + "aws-smithy-query 0.60.6", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "aws-smithy-xml 0.60.6", + "aws-types 1.1.7", + "http 0.2.9", + "once_cell", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sig-auth" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b94acb10af0c879ecd5c7bdf51cda6679a0a4f4643ce630905a77673bfa3c61" dependencies = [ - "aws-credential-types", - "aws-sigv4", + "aws-credential-types 0.55.3", + "aws-sigv4 0.55.3", "aws-smithy-eventstream", - "aws-smithy-http", - "aws-types", - "http", + "aws-smithy-http 0.55.3", + "aws-types 0.55.3", + "http 0.2.9", "tracing", ] @@ -893,12 +1023,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d2ce6f507be68e968a33485ced670111d1cbad161ddbbab1e313c03d37d8f4c" dependencies = [ "aws-smithy-eventstream", - "aws-smithy-http", + "aws-smithy-http 0.55.3", "bytes 1.5.0", "form_urlencoded", "hex", "hmac", - "http", + "http 0.2.9", "once_cell", "percent-encoding", "regex", @@ -907,6 +1037,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sigv4" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ada00a4645d7d89f296fe0ddbc3fe3554f03035937c849a05d37ddffc1f29a1" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "bytes 1.5.0", + "form_urlencoded", + "hex", + "hmac", + "http 0.2.9", + "http 1.0.0", + "once_cell", + "percent-encoding", + "sha2", + "time", + "tracing", +] + [[package]] name = "aws-smithy-async" version = "0.55.3" @@ -919,19 +1072,30 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "aws-smithy-async" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcf7f09a27286d84315dfb9346208abb3b0973a692454ae6d0bc8d803fcce3b4" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio 1.36.0", +] + [[package]] name = "aws-smithy-checksums" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07ed8b96d95402f3f6b8b57eb4e0e45ee365f78b1a924faf20ff6e97abf1eae6" dependencies = [ - "aws-smithy-http", - "aws-smithy-types", + "aws-smithy-http 0.55.3", + "aws-smithy-types 0.55.3", "bytes 1.5.0", "crc32c", "crc32fast", "hex", - "http", + "http 0.2.9", "http-body", "md-5", "pin-project-lite", @@ -946,13 +1110,13 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a86aa6e21e86c4252ad6a0e3e74da9617295d8d6e374d552be7d3059c41cedd" dependencies = [ - "aws-smithy-async", - "aws-smithy-http", + "aws-smithy-async 0.55.3", + "aws-smithy-http 0.55.3", "aws-smithy-http-tower", - "aws-smithy-types", + "aws-smithy-types 0.55.3", "bytes 1.5.0", "fastrand 1.9.0", - "http", + "http 0.2.9", "http-body", "hyper", "hyper-rustls 0.23.2", @@ -970,7 +1134,7 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460c8da5110835e3d9a717c61f5556b20d03c32a1dec57f8fc559b360f733bb8" dependencies = [ - "aws-smithy-types", + "aws-smithy-types 0.55.3", "bytes 1.5.0", "crc32fast", ] @@ -982,11 +1146,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b3b693869133551f135e1f2c77cb0b8277d9e3e17feaf2213f735857c4f0d28" dependencies = [ "aws-smithy-eventstream", - "aws-smithy-types", + "aws-smithy-types 0.55.3", "bytes 1.5.0", "bytes-utils", "futures-core", - "http", + "http 0.2.9", "http-body", "hyper", "once_cell", @@ -998,16 +1162,36 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-smithy-http" +version = "0.60.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6ca214a6a26f1b7ebd63aa8d4f5e2194095643023f9608edf99a58247b9d80d" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "bytes 1.5.0", + "bytes-utils", + "futures-core", + "http 0.2.9", + "http-body", + "once_cell", + "percent-encoding", + "pin-project-lite", + "pin-utils", + "tracing", +] + [[package]] name = "aws-smithy-http-tower" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ae4f6c5798a247fac98a867698197d9ac22643596dc3777f0c76b91917616b9" dependencies = [ - "aws-smithy-http", - "aws-smithy-types", + "aws-smithy-http 0.55.3", + "aws-smithy-types 0.55.3", "bytes 1.5.0", - "http", + "http 0.2.9", "http-body", "pin-project-lite", "tower", @@ -1020,7 +1204,16 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23f9f42fbfa96d095194a632fbac19f60077748eba536eb0b9fecc28659807f8" dependencies = [ - "aws-smithy-types", + "aws-smithy-types 0.55.3", +] + +[[package]] +name = "aws-smithy-json" +version = "0.60.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1af80ecf3057fb25fe38d1687e94c4601a7817c6a1e87c1b0635f7ecb644ace5" +dependencies = [ + "aws-smithy-types 1.1.7", ] [[package]] @@ -1029,10 +1222,62 @@ version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98819eb0b04020a1c791903533b638534ae6c12e2aceda3e6e6fba015608d51d" dependencies = [ - "aws-smithy-types", + "aws-smithy-types 0.55.3", "urlencoding", ] +[[package]] +name = "aws-smithy-query" +version = "0.60.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb27084f72ea5fc20033efe180618677ff4a2f474b53d84695cfe310a6526cbc" +dependencies = [ + "aws-smithy-types 1.1.7", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbb5fca54a532a36ff927fbd7407a7c8eb9c3b4faf72792ba2965ea2cad8ed55" +dependencies = [ + "aws-smithy-async 1.1.7", + "aws-smithy-http 0.60.6", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "bytes 1.5.0", + "fastrand 2.0.1", + "h2", + "http 0.2.9", + "http-body", + "hyper", + "hyper-rustls 0.24.2", + "once_cell", + "pin-project-lite", + "pin-utils", + "rustls 0.21.10", + "tokio 1.36.0", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22389cb6f7cac64f266fb9f137745a9349ced7b47e0d2ba503e9e40ede4f7060" +dependencies = [ + "aws-smithy-async 1.1.7", + "aws-smithy-types 1.1.7", + "bytes 1.5.0", + "http 0.2.9", + "http 1.0.0", + "pin-project-lite", + "tokio 1.36.0", + "tracing", + "zeroize", +] + [[package]] name = "aws-smithy-types" version = "0.55.3" @@ -1046,6 +1291,29 @@ dependencies = [ "time", ] +[[package]] +name = "aws-smithy-types" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f081da5481210523d44ffd83d9f0740320050054006c719eae0232d411f024d3" +dependencies = [ + "base64-simd", + "bytes 1.5.0", + "bytes-utils", + "futures-core", + "http 0.2.9", + "http-body", + "itoa", + "num-integer", + "pin-project-lite", + "pin-utils", + "ryu", + "serde", + "time", + "tokio 1.36.0", + "tokio-util", +] + [[package]] name = "aws-smithy-xml" version = "0.55.3" @@ -1055,18 +1323,42 @@ dependencies = [ "xmlparser", ] +[[package]] +name = "aws-smithy-xml" +version = "0.60.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fccd8f595d0ca839f9f2548e66b99514a85f92feb4c01cf2868d93eb4888a42" +dependencies = [ + "xmlparser", +] + [[package]] name = "aws-types" version = "0.55.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dd209616cc8d7bfb82f87811a5c655dc97537f592689b18743bddf5dc5c4829" dependencies = [ - "aws-credential-types", - "aws-smithy-async", + "aws-credential-types 0.55.3", + "aws-smithy-async 0.55.3", "aws-smithy-client", - "aws-smithy-http", - "aws-smithy-types", - "http", + "aws-smithy-http 0.55.3", + "aws-smithy-types 0.55.3", + "http 0.2.9", + "rustc_version 0.4.0", + "tracing", +] + +[[package]] +name = "aws-types" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07c63521aa1ea9a9f92a701f1a08ce3fd20b46c6efc0d5c8947c1fd879e3df1" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-smithy-async 1.1.7", + "aws-smithy-runtime-api", + "aws-smithy-types 1.1.7", + "http 0.2.9", "rustc_version 0.4.0", "tracing", ] @@ -1082,7 +1374,7 @@ dependencies = [ "bitflags 1.3.2", "bytes 1.5.0", "futures-util", - "http", + "http 0.2.9", "http-body", "hyper", "itoa", @@ -1108,7 +1400,7 @@ dependencies = [ "async-trait", "bytes 1.5.0", "futures-util", - "http", + "http 0.2.9", "http-body", "mime", "rustversion", @@ -1663,7 +1955,7 @@ dependencies = [ "fake", "futures 0.3.28", "hex", - "http", + "http 0.2.9", "masking", "md5", "nanoid", @@ -1674,7 +1966,7 @@ dependencies = [ "rand 0.8.5", "regex", "reqwest", - "ring", + "ring 0.16.20", "router_env", "rustc-hash", "serde", @@ -2494,11 +2786,11 @@ name = "external_services" version = "0.1.0" dependencies = [ "async-trait", - "aws-config", + "aws-config 0.55.3", "aws-sdk-kms", "aws-sdk-s3", "aws-sdk-sesv2", - "aws-sdk-sts", + "aws-sdk-sts 0.28.0", "aws-smithy-client", "base64 0.21.5", "common_utils", @@ -2537,7 +2829,7 @@ dependencies = [ "cookie 0.16.2", "futures-core", "futures-util", - "http", + "http 0.2.9", "hyper", "hyper-rustls 0.23.2", "mime", @@ -2962,7 +3254,7 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http", + "http 0.2.9", "indexmap 2.1.0", "slab", "tokio 1.36.0", @@ -3013,7 +3305,7 @@ dependencies = [ "base64 0.21.5", "bytes 1.5.0", "headers-core", - "http", + "http 0.2.9", "httpdate", "mime", "sha1", @@ -3025,7 +3317,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" dependencies = [ - "http", + "http 0.2.9", ] [[package]] @@ -3078,6 +3370,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b32afd38673a8016f7c9ae69e5af41a58f81b1d31689040f2f1959594ce194ea" +dependencies = [ + "bytes 1.5.0", + "fnv", + "itoa", +] + [[package]] name = "http-body" version = "0.4.5" @@ -3085,7 +3388,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ "bytes 1.5.0", - "http", + "http 0.2.9", "pin-project-lite", ] @@ -3099,7 +3402,7 @@ dependencies = [ "async-channel", "base64 0.13.1", "futures-lite", - "http", + "http 0.2.9", "infer 0.2.3", "pin-project-lite", "rand 0.7.3", @@ -3142,7 +3445,7 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.9", "http-body", "httparse", "httpdate", @@ -3164,7 +3467,7 @@ dependencies = [ "bytes 1.5.0", "futures 0.3.28", "headers", - "http", + "http 0.2.9", "hyper", "hyper-tls", "native-tls", @@ -3179,7 +3482,7 @@ version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" dependencies = [ - "http", + "http 0.2.9", "hyper", "log", "rustls 0.20.9", @@ -3195,9 +3498,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ "futures-util", - "http", + "http 0.2.9", "hyper", - "rustls 0.21.7", + "log", + "rustls 0.21.10", + "rustls-native-certs", "tokio 1.36.0", "tokio-rustls 0.24.1", ] @@ -3508,7 +3813,7 @@ checksum = "6971da4d9c3aa03c3d8f3ff0f4155b534aad021292003895a469716b2a230378" dependencies = [ "base64 0.21.5", "pem", - "ring", + "ring 0.16.20", "serde", "serde_json", "simple_asn1", @@ -4111,6 +4416,30 @@ dependencies = [ "utoipa", ] +[[package]] +name = "opensearch" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd2846759315751e04d8b45a0bdbd89ce442282ffb916cf54f6b0adf8df4b44c" +dependencies = [ + "aws-credential-types 1.1.7", + "aws-sigv4 1.1.7", + "aws-smithy-runtime-api", + "aws-types 1.1.7", + "base64 0.21.5", + "bytes 1.5.0", + "dyn-clone", + "lazy_static", + "percent-encoding", + "reqwest", + "rustc_version 0.4.0", + "serde", + "serde_json", + "serde_with", + "url", + "void", +] + [[package]] name = "openssl" version = "0.10.60" @@ -4174,7 +4503,7 @@ dependencies = [ "async-trait", "futures 0.3.28", "futures-util", - "http", + "http 0.2.9", "opentelemetry", "opentelemetry-proto", "prost", @@ -4569,7 +4898,7 @@ dependencies = [ "common_enums", "common_utils", "error-stack", - "http", + "http 0.2.9", "masking", "mime", "router_derive", @@ -5058,6 +5387,12 @@ dependencies = [ "regex-syntax 0.6.29", ] +[[package]] +name = "regex-lite" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e" + [[package]] name = "regex-syntax" version = "0.6.29" @@ -5098,7 +5433,7 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.9", "http-body", "hyper", "hyper-rustls 0.24.2", @@ -5112,7 +5447,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls 0.21.7", + "rustls 0.21.10", "rustls-pemfile", "serde", "serde_json", @@ -5146,12 +5481,27 @@ dependencies = [ "cc", "libc", "once_cell", - "spin", - "untrusted", + "spin 0.5.2", + "untrusted 0.7.1", "web-sys", "winapi 0.3.9", ] +[[package]] +name = "ring" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if 1.0.0", + "getrandom 0.2.11", + "libc", + "spin 0.9.8", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + [[package]] name = "rkyv" version = "0.7.42" @@ -5244,7 +5594,7 @@ dependencies = [ "external_services", "futures 0.3.28", "hex", - "http", + "http 0.2.9", "hyper", "hyperswitch_interfaces", "image", @@ -5272,7 +5622,7 @@ dependencies = [ "redis_interface", "regex", "reqwest", - "ring", + "ring 0.16.20", "router_derive", "router_env", "roxmltree", @@ -5429,7 +5779,7 @@ dependencies = [ "anyhow", "async-trait", "bytes 1.5.0", - "http", + "http 0.2.9", "reqwest", "rustify_derive", "serde", @@ -5474,19 +5824,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" dependencies = [ "log", - "ring", + "ring 0.16.20", "sct", "webpki", ] [[package]] name = "rustls" -version = "0.21.7" +version = "0.21.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" +checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" dependencies = [ "log", - "ring", + "ring 0.17.8", "rustls-webpki", "sct", ] @@ -5514,12 +5864,12 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.101.6" +version = "0.101.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" dependencies = [ - "ring", - "untrusted", + "ring 0.17.8", + "untrusted 0.9.0", ] [[package]] @@ -5625,8 +5975,8 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" dependencies = [ - "ring", - "untrusted", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] @@ -6025,6 +6375,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + [[package]] name = "sqlformat" version = "0.2.2" @@ -6149,13 +6505,13 @@ dependencies = [ "dyn-clone", "error-stack", "futures 0.3.28", - "http", + "http 0.2.9", "masking", "mime", "moka", "once_cell", "redis_interface", - "ring", + "ring 0.16.20", "router_derive", "router_env", "serde", @@ -6428,7 +6784,7 @@ dependencies = [ "cookie 0.16.2", "fantoccini", "futures 0.3.28", - "http", + "http 0.2.9", "log", "parking_lot 0.12.1", "serde", @@ -6710,7 +7066,7 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.7", + "rustls 0.21.10", "tokio 1.36.0", ] @@ -6895,7 +7251,7 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.9", "http-body", "hyper", "hyper-timeout", @@ -7211,6 +7567,12 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.4.1" @@ -7300,7 +7662,7 @@ dependencies = [ "async-trait", "bytes 1.5.0", "derive_builder", - "http", + "http 0.2.9", "reqwest", "rustify", "rustify_derive", @@ -7336,6 +7698,12 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + [[package]] name = "vsimd" version = "0.8.0" @@ -7473,7 +7841,7 @@ dependencies = [ "base64 0.13.1", "bytes 1.5.0", "cookie 0.16.2", - "http", + "http 0.2.9", "log", "serde", "serde_derive", @@ -7489,8 +7857,8 @@ version = "0.22.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07ecc0cd7cac091bf682ec5efa18b1cff79d617b84181f38b3951dbe135f607f" dependencies = [ - "ring", - "untrusted", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] diff --git a/config/config.example.toml b/config/config.example.toml index 2ffb69c3e3d..daf554f00ad 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -54,10 +54,10 @@ use_legacy_version = false # Resp protocol for fred crate (set this to tr stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. -max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds -unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. # This section provides configs for currency conversion api [forex_api] @@ -298,9 +298,9 @@ lock_ttl = 160 # the ttl being the expiry (in seconds) # Scheduler server configuration [scheduler.server] -port = 3000 # Port on which the server will listen for incoming requests -host = "127.0.0.1" # Host IP address to bind the server to -workers = 1 # Number of actix workers to handle incoming requests concurrently +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently batch_size = 200 # Specifies the batch size the producer will push under a single entry in the redis queue @@ -321,10 +321,10 @@ paypal = { currency = "USD,INR", country = "US" } # If either currency or country isn't provided then, all possible values are accepted [cors] -max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. -origins = "http://localhost:8080" # List of origins that are allowed to make requests. +max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. +origins = "http://localhost:8080" # List of origins that are allowed to make requests. allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed -wildcard_origin = false # If true, allows any origin to make requests +wildcard_origin = false # If true, allows any origin to make requests # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] @@ -357,7 +357,7 @@ bluesnap = { payment_method = "card" } bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi = { payment_method = "card" } -payme = {payment_method = "card" } +payme = { payment_method = "card" } [dummy_connector] enabled = true # Whether dummy connector is enabled or not @@ -380,21 +380,21 @@ slack_invite_url = "https://www.example.com/" # Slack invite url for hyperswit discord_invite_url = "https://www.example.com/" # Discord invite url for hyperswitch [mandates.supported_payment_methods] -card.credit = { connector_list = "stripe,adyen,cybersource" } # Mandate supported payment method type and connector for card -wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets -pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later -bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit -bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit -bank_debit.sepa = { connector_list = "gocardless" } # 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,adyen,globalpay"} +card.credit = { connector_list = "stripe,adyen,cybersource" } # Mandate supported payment method type and connector for card +wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets +pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later +bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit +bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit +bank_debit.sepa = { connector_list = "gocardless" } # 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,adyen,globalpay" } wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } -bank_redirect.giropay = {connector_list = "adyen,globalpay"} +bank_redirect.giropay = { connector_list = "adyen,globalpay" } [mandates.update_mandate_supported] -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 +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 # Required fields info used while listing the payment_method_data [required_fields.pay_later] # payment_method = "pay_later" @@ -412,9 +412,9 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility [pm_filters.adyen] -sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } -klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" } ideal = { country = "NL", currency = "EUR" } online_banking_fpx = { country = "MY", currency = "MYR" } online_banking_thailand = { country = "TH", currency = "THB" } @@ -442,7 +442,7 @@ pay_easy = { country = "JP", currency = "JPY" } boleto = { country = "BR", currency = "BRL" } [pm_filters.volt] -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"} +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" } } @@ -566,22 +566,36 @@ dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute event # File storage configuration [file_storage] -file_storage_backend = "aws_s3" # File storage backend to be used +file_storage_backend = "aws_s3" # File storage backend to be used [file_storage.aws_s3] -region = "us-east-1" # The AWS region used by the AWS S3 for file storage -bucket_name = "bucket1" # The AWS S3 bucket name for file storage +region = "us-east-1" # The AWS region used by the AWS S3 for file storage +bucket_name = "bucket1" # The AWS S3 bucket name for file storage [secrets_management] -secrets_manager = "aws_kms" # Secrets manager client to be used +secrets_manager = "aws_kms" # Secrets manager client to be used [secrets_management.aws_kms] -key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. -region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [encryption_management] -encryption_manager = "aws_kms" # Encryption manager client to be used +encryption_manager = "aws_kms" # Encryption manager client to be used [encryption_management.aws_kms] -key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. -region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. + +[opensearch] +host = "https://localhost:9200" + +[opensearch.auth] +auth = "basic" +username = "admin" +password = "admin" +region = "eu-central-1" + +[opensearch.indexes] +payment_attempts = "hyperswitch-payment-attempt-events" +payment_intents = "hyperswitch-payment-intent-events" +refunds = "hyperswitch-refund-events" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 990796c79bc..cfe696e42c0 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -42,13 +42,17 @@ client_secret = "paypal_client_secret" partner_id = "paypal_partner_id" [connector_request_reference_id_config] -merchant_ids_send_payment_id_as_connector_request_id = ["merchant_id_1", "merchant_id_2", "etc.,"] +merchant_ids_send_payment_id_as_connector_request_id = [ + "merchant_id_1", + "merchant_id_2", + "etc.,", +] [cors] -max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. -origins = "http://localhost:8080" # List of origins that are allowed to make requests. +max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. +origins = "http://localhost:8080" # List of origins that are allowed to make requests. allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed -wildcard_origin = false # If true, allows any origin to make requests +wildcard_origin = false # If true, allows any origin to make requests # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] @@ -160,21 +164,24 @@ https_url = "https://proxy_https_url" # Outgoing proxy https URL to proxy the HT [redis] host = "127.0.0.1" port = 6379 -pool_size = 5 # Number of connections to keep open -reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever. -reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds -default_ttl = 300 # Default TTL for entries, in seconds -default_hash_ttl = 900 # Default TTL for hashes entries, in seconds -use_legacy_version = false # RESP protocol for fred crate (set this to true if using RESPv2 or redis version < 6) -stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options -auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. -disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. +pool_size = 5 # Number of connections to keep open +reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever. +reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds +default_ttl = 300 # Default TTL for entries, in seconds +default_hash_ttl = 900 # Default TTL for hashes entries, in seconds +use_legacy_version = false # RESP protocol for fred crate (set this to true if using RESPv2 or redis version < 6) +stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options +auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. +disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. -cluster_enabled = true # boolean -cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List of redis cluster urls +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +cluster_enabled = true # boolean +cluster_urls = [ + "redis.cluster.uri-1:8080", + "redis.cluster.uri-2:4115", +] # List of redis cluster urls # Replica SQL data store credentials [replica_database] @@ -193,6 +200,20 @@ payment_function = "report_download_config_payment_function" # Config to downloa refund_function = "report_download_config_refund_function" # Config to download refund report region = "report_download_config_region" # Region of the bucket +[opensearch] +host = "https://localhost:9200" + +[opensearch.auth] +auth = "basic" +username = "admin" +password = "admin" +region = "eu-central-1" + +[opensearch.indexes] +payment_attempts = "hyperswitch-payment-attempt-events" +payment_intents = "hyperswitch-payment-intent-events" +refunds = "hyperswitch-refund-events" + # This section provides some secret values. [secrets] master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long. @@ -213,15 +234,15 @@ shutdown_timeout = 30 request_body_limit = 32_768 [secrets_management] -secrets_manager = "aws_kms" # Secrets manager client to be used +secrets_manager = "aws_kms" # Secrets manager client to be used [secrets_management.aws_kms] -key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. -region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [encryption_management] -encryption_manager = "aws_kms" # Encryption manager client to be used +encryption_manager = "aws_kms" # Encryption manager client to be used [encryption_management.aws_kms] -key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. -region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. +region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. diff --git a/config/development.toml b/config/development.toml index 16851c90cca..a7abec7fb74 100644 --- a/config/development.toml +++ b/config/development.toml @@ -273,7 +273,7 @@ adyen = { banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24, stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" } [bank_config.open_banking_uk] -adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"} +adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" } [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -306,7 +306,7 @@ ideal = { country = "NL", currency = "EUR" } cashapp = { country = "US", currency = "USD" } [pm_filters.volt] -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"} +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" } @@ -316,54 +316,54 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" } affirm = { country = "US", currency = "USD" } afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = {not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +sofort = { not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } ideal = { not_available_flows = { capture_method = "manual" }, country = "NL", currency = "EUR" } -blik = {country = "PL", currency = "PLN"} -trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} -online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"} -online_banking_finland = {country = "FI", currency = "EUR"} -online_banking_poland = {country = "PL", currency = "PLN"} -online_banking_slovakia = {country = "SK", currency = "EUR,CZK"} -bancontact_card = {country = "BE", currency = "EUR"} -ach = {country = "US", currency = "USD"} -bacs = {country = "GB", currency = "GBP"} -sepa = {country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR"} -ali_pay_hk = {country = "HK", currency = "HKD"} -bizum = {country = "ES", currency = "EUR"} -go_pay = {country = "ID", currency = "IDR"} -kakao_pay = {country = "KR", currency = "KRW"} -momo = {country = "VN", currency = "VND"} -gcash = {country = "PH", currency = "PHP"} -online_banking_fpx = {country = "MY", currency = "MYR"} -online_banking_thailand = {country = "TH", currency = "THB"} -touch_n_go = {country = "MY", currency = "MYR"} -atome = {country = "MY,SG", currency = "MYR,SGD"} -swish = {country = "SE", currency = "SEK"} -permata_bank_transfer = {country = "ID", currency = "IDR"} -bca_bank_transfer = {country = "ID", currency = "IDR"} -bni_va = {country = "ID", currency = "IDR"} -bri_va = {country = "ID", currency = "IDR"} -cimb_va = {country = "ID", currency = "IDR"} -danamon_va = {country = "ID", currency = "IDR"} -mandiri_va = {country = "ID", currency = "IDR"} -alfamart = {country = "ID", currency = "IDR"} -indomaret = {country = "ID", currency = "IDR"} -open_banking_uk = {country = "GB", currency = "GBP"} -oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} -seven_eleven = {country = "JP", currency = "JPY"} -lawson = {country = "JP", currency = "JPY"} -mini_stop = {country = "JP", currency = "JPY"} -family_mart = {country = "JP", currency = "JPY"} -seicomart = {country = "JP", currency = "JPY"} -pay_easy = {country = "JP", currency = "JPY"} +blik = { country = "PL", currency = "PLN" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" } +online_banking_finland = { country = "FI", currency = "EUR" } +online_banking_poland = { country = "PL", currency = "PLN" } +online_banking_slovakia = { country = "SK", currency = "EUR,CZK" } +bancontact_card = { country = "BE", currency = "EUR" } +ach = { country = "US", currency = "USD" } +bacs = { country = "GB", currency = "GBP" } +sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } +ali_pay_hk = { country = "HK", currency = "HKD" } +bizum = { country = "ES", currency = "EUR" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } +gcash = { country = "PH", currency = "PHP" } +online_banking_fpx = { country = "MY", currency = "MYR" } +online_banking_thailand = { country = "TH", currency = "THB" } +touch_n_go = { country = "MY", currency = "MYR" } +atome = { country = "MY,SG", currency = "MYR,SGD" } +swish = { country = "SE", currency = "SEK" } +permata_bank_transfer = { country = "ID", currency = "IDR" } +bca_bank_transfer = { country = "ID", currency = "IDR" } +bni_va = { country = "ID", currency = "IDR" } +bri_va = { country = "ID", currency = "IDR" } +cimb_va = { country = "ID", currency = "IDR" } +danamon_va = { country = "ID", currency = "IDR" } +mandiri_va = { country = "ID", currency = "IDR" } +alfamart = { country = "ID", currency = "IDR" } +indomaret = { country = "ID", currency = "IDR" } +open_banking_uk = { country = "GB", currency = "GBP" } +oxxo = { country = "MX", currency = "MXN" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +seven_eleven = { country = "JP", currency = "JPY" } +lawson = { country = "JP", currency = "JPY" } +mini_stop = { country = "JP", currency = "JPY" } +family_mart = { country = "JP", currency = "JPY" } +seicomart = { country = "JP", currency = "JPY" } +pay_easy = { country = "JP", currency = "JPY" } pix = { country = "BR", currency = "BRL" } boleto = { country = "BR", currency = "BRL" } @@ -443,21 +443,21 @@ debit = { currency = "USD" } stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } stax = { long_lived_token = true, payment_method = "card,bank_debit" } -mollie = {long_lived_token = false, payment_method = "card"} -square = {long_lived_token = false, payment_method = "card"} +mollie = { long_lived_token = false, payment_method = "card" } +square = { long_lived_token = false, payment_method = "card" } braintree = { long_lived_token = false, payment_method = "card" } -payme = {long_lived_token = false, payment_method = "card"} -gocardless = {long_lived_token = true, payment_method = "bank_debit"} +payme = { long_lived_token = false, payment_method = "card" } +gocardless = { long_lived_token = true, payment_method = "bank_debit" } [temp_locker_enable_config] -stripe = {payment_method = "bank_transfer"} -nuvei = {payment_method = "card"} -shift4 = {payment_method = "card"} -bluesnap = {payment_method = "card"} -bankofamerica = {payment_method = "card"} -cybersource = {payment_method = "card"} -nmi = {payment_method = "card"} -payme = {payment_method = "card"} +stripe = { payment_method = "bank_transfer" } +nuvei = { payment_method = "card" } +shift4 = { payment_method = "card" } +bluesnap = { payment_method = "card" } +bankofamerica = { payment_method = "card" } +cybersource = { payment_method = "card" } +nmi = { payment_method = "card" } +payme = { payment_method = "card" } [connector_customer] connector_list = "gocardless,stax,stripe" @@ -496,16 +496,16 @@ wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } wallet.paypal = { connector_list = "adyen" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } -bank_debit.ach = { connector_list = "gocardless"} -bank_debit.becs = { connector_list = "gocardless"} -bank_debit.sepa = { connector_list = "gocardless"} -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.giropay = {connector_list = "adyen,globalpay"} +bank_debit.ach = { connector_list = "gocardless" } +bank_debit.becs = { connector_list = "gocardless" } +bank_debit.sepa = { connector_list = "gocardless" } +bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } +bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" } +bank_redirect.giropay = { connector_list = "adyen,globalpay" } [mandates.update_mandate_supported] -card.credit ={connector_list ="cybersource"} -card.debit = {connector_list ="cybersource"} +card.credit = { connector_list = "cybersource" } +card.debit = { connector_list = "cybersource" } [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] @@ -530,7 +530,7 @@ redis_expiry = 900 pm_auth_key = "Some_pm_auth_key" [lock_settings] -redis_lock_expiry_seconds = 180 # 3 * 60 seconds +redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 [kv_config] @@ -582,3 +582,17 @@ file_storage_backend = "file_system" [unmasked_headers] keys = "user-agent" + +[opensearch] +host = "https://localhost:9200" + +[opensearch.auth] +auth = "basic" +username = "admin" +password = "admin" +region = "eu-central-1" + +[opensearch.indexes] +payment_attempts = "hyperswitch-payment-attempt-events" +payment_intents = "hyperswitch-payment-intent-events" +refunds = "hyperswitch-refund-events" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2f94d69790b..4d1731b53ff 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -15,7 +15,7 @@ level = "DEBUG" # What you see in your terminal. [log.telemetry] traces_enabled = false # Whether traces are enabled. -metrics_enabled = true # Whether metrics are enabled. +metrics_enabled = true # Whether metrics are enabled. ignore_errors = false # Whether to ignore errors during traces or metrics pipeline setup. otel_exporter_otlp_endpoint = "https://otel-collector:4317" # Endpoint to send metrics and traces to. use_xray_generator = false @@ -244,21 +244,21 @@ workers = 1 [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } -mollie = {long_lived_token = false, payment_method = "card"} +mollie = { long_lived_token = false, payment_method = "card" } stax = { long_lived_token = true, payment_method = "card,bank_debit" } -square = {long_lived_token = false, payment_method = "card"} +square = { long_lived_token = false, payment_method = "card" } braintree = { long_lived_token = false, payment_method = "card" } -gocardless = {long_lived_token = true, payment_method = "bank_debit"} +gocardless = { long_lived_token = true, payment_method = "bank_debit" } [temp_locker_enable_config] -stripe = {payment_method = "bank_transfer"} -nuvei = {payment_method = "card"} -shift4 = {payment_method = "card"} -bluesnap = {payment_method = "card"} -bankofamerica = {payment_method = "card"} -cybersource = {payment_method = "card"} -nmi = {payment_method = "card"} -payme = {payment_method = "card"} +stripe = { payment_method = "bank_transfer" } +nuvei = { payment_method = "card" } +shift4 = { payment_method = "card" } +bluesnap = { payment_method = "card" } +bankofamerica = { payment_method = "card" } +cybersource = { payment_method = "card" } +nmi = { payment_method = "card" } +payme = { payment_method = "card" } [dummy_connector] enabled = true @@ -284,38 +284,38 @@ discord_invite_url = "https://discord.gg/wJZ7DVW8mm" payout_eligibility = true [pm_filters.adyen] -online_banking_fpx = {country = "MY", currency = "MYR"} -online_banking_thailand = {country = "TH", currency = "THB"} -touch_n_go = {country = "MY", currency = "MYR"} -atome = {country = "MY,SG", currency = "MYR,SGD"} -swish = {country = "SE", currency = "SEK"} -permata_bank_transfer = {country = "ID", currency = "IDR"} -bca_bank_transfer = {country = "ID", currency = "IDR"} -bni_va = {country = "ID", currency = "IDR"} -bri_va = {country = "ID", currency = "IDR"} -cimb_va = {country = "ID", currency = "IDR"} -danamon_va = {country = "ID", currency = "IDR"} -mandiri_va = {country = "ID", currency = "IDR"} -alfamart = {country = "ID", currency = "IDR"} -indomaret = {country = "ID", currency = "IDR"} -open_banking_uk = {country = "GB", currency = "GBP"} -oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} -seven_eleven = {country = "JP", currency = "JPY"} -lawson = {country = "JP", currency = "JPY"} -mini_stop = {country = "JP", currency = "JPY"} -family_mart = {country = "JP", currency = "JPY"} -seicomart = {country = "JP", currency = "JPY"} -pay_easy = {country = "JP", currency = "JPY"} +online_banking_fpx = { country = "MY", currency = "MYR" } +online_banking_thailand = { country = "TH", currency = "THB" } +touch_n_go = { country = "MY", currency = "MYR" } +atome = { country = "MY,SG", currency = "MYR,SGD" } +swish = { country = "SE", currency = "SEK" } +permata_bank_transfer = { country = "ID", currency = "IDR" } +bca_bank_transfer = { country = "ID", currency = "IDR" } +bni_va = { country = "ID", currency = "IDR" } +bri_va = { country = "ID", currency = "IDR" } +cimb_va = { country = "ID", currency = "IDR" } +danamon_va = { country = "ID", currency = "IDR" } +mandiri_va = { country = "ID", currency = "IDR" } +alfamart = { country = "ID", currency = "IDR" } +indomaret = { country = "ID", currency = "IDR" } +open_banking_uk = { country = "GB", currency = "GBP" } +oxxo = { country = "MX", currency = "MXN" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +seven_eleven = { country = "JP", currency = "JPY" } +lawson = { country = "JP", currency = "JPY" } +mini_stop = { country = "JP", currency = "JPY" } +family_mart = { country = "JP", currency = "JPY" } +seicomart = { country = "JP", currency = "JPY" } +pay_easy = { country = "JP", currency = "JPY" } boleto = { country = "BR", currency = "BRL" } ideal = { country = "NL", currency = "EUR" } -klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" } paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } -sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } [pm_filters.volt] -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"} +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" } } @@ -330,7 +330,7 @@ red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } [pm_filters.stripe] -cashapp = {country = "US", currency = "USD"} +cashapp = { country = "US", currency = "USD" } [pm_filters.prophetpay] card_redirect = { currency = "USD" } @@ -357,25 +357,25 @@ adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamal adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" [bank_config.open_banking_uk] -adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"} +adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" } [mandates.supported_payment_methods] -pay_later.klarna = {connector_list = "adyen"} -wallet.google_pay = {connector_list = "stripe,adyen"} -wallet.apple_pay = {connector_list = "stripe,adyen,cybersource,noon"} -wallet.paypal = {connector_list = "adyen"} -card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} -card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} -bank_debit.ach = { connector_list = "gocardless"} -bank_debit.becs = { connector_list = "gocardless"} -bank_debit.sepa = { connector_list = "gocardless"} -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.giropay = {connector_list = "adyen,globalpay"} +pay_later.klarna = { connector_list = "adyen" } +wallet.google_pay = { connector_list = "stripe,adyen" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } +wallet.paypal = { connector_list = "adyen" } +card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } +card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } +bank_debit.ach = { connector_list = "gocardless" } +bank_debit.becs = { connector_list = "gocardless" } +bank_debit.sepa = { connector_list = "gocardless" } +bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } +bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" } +bank_redirect.giropay = { connector_list = "adyen,globalpay" } [mandates.update_mandate_supported] -card.credit ={connector_list ="cybersource"} -card.debit = {connector_list ="cybersource"} +card.credit = { connector_list = "cybersource" } +card.debit = { connector_list = "cybersource" } [connector_customer] connector_list = "gocardless,stax,stripe" @@ -389,7 +389,7 @@ redis_expiry = 900 pm_auth_key = "Some_pm_auth_key" [lock_settings] -redis_lock_expiry_seconds = 180 # 3 * 60 seconds +redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 [events.kafka] @@ -440,4 +440,18 @@ source = "logs" file_storage_backend = "file_system" [unmasked_headers] -keys = "user-agent" \ No newline at end of file +keys = "user-agent" + +[opensearch] +host = "https://opensearch:9200" + +[opensearch.auth] +auth = "basic" +username = "admin" +password = "admin" +region = "eu-central-1" + +[opensearch.indexes] +payment_attempts = "hyperswitch-payment-attempt-events" +payment_intents = "hyperswitch-payment-intent-events" +refunds = "hyperswitch-refund-events" \ No newline at end of file diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index f3e01492135..f07e0a94ea5 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "analytics" version = "0.1.0" -description = "Analytics / Reports related functionality" +description = "Analytics / Reports / Search related functionality" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -9,29 +9,43 @@ edition = "2021" [dependencies] # First party crates -api_models = { version = "0.1.0", path = "../api_models" , features = ["errors"]} +api_models = { version = "0.1.0", path = "../api_models", features = [ + "errors", +] } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } common_utils = { version = "0.1.0", path = "../common_utils" } external_services = { version = "0.1.0", path = "../external_services", default-features = false } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } masking = { version = "0.1.0", path = "../masking" } -router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +router_env = { version = "0.1.0", path = "../router_env", features = [ + "log_extra_implicit_fields", + "log_custom_entries_to_extra", +] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = [ + "kv_store", +] } #Third Party dependencies actix-web = "4.3.1" async-trait = "0.1.68" -aws-config = { version = "0.55.3" } -aws-sdk-lambda = { version = "0.28.0" } -aws-smithy-types = { version = "0.55.3" } +aws-config = { version = "1.1.6", features = ["behavior-version-latest"] } +aws-sdk-lambda = { version = "1.1.4" } +aws-smithy-types = { version = "1.1.6" } bigdecimal = { version = "0.3.1", features = ["serde"] } error-stack = "0.3.1" futures = "0.3.28" +opensearch = { version = "2.2.0", features = ["aws-auth"] } once_cell = "1.18.0" reqwest = { version = "0.11.18", features = ["serde_json"] } serde = { version = "1.0.193", features = ["derive", "rc"] } serde_json = "1.0.108" -sqlx = { version = "0.6.3", features = ["postgres", "runtime-actix", "runtime-actix-native-tls", "time", "bigdecimal"] } +sqlx = { version = "0.6.3", features = [ + "postgres", + "runtime-actix", + "runtime-actix-native-tls", + "time", + "bigdecimal", +] } strum = { version = "0.25.0", features = ["derive"] } thiserror = "1.0.43" time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } diff --git a/crates/analytics/src/lambda_utils.rs b/crates/analytics/src/lambda_utils.rs index f9446a402b4..4f8320f29b5 100644 --- a/crates/analytics/src/lambda_utils.rs +++ b/crates/analytics/src/lambda_utils.rs @@ -1,5 +1,5 @@ -use aws_config::{self, meta::region::RegionProviderChain}; -use aws_sdk_lambda::{config::Region, types::InvocationType::Event, Client}; +use aws_config::{self, meta::region::RegionProviderChain, Region}; +use aws_sdk_lambda::{types::InvocationType::Event, Client}; use aws_smithy_types::Blob; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index d8de32a732b..68ca51a0df0 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -12,6 +12,7 @@ pub mod connector_events; pub mod health_check; pub mod outgoing_webhook_event; pub mod sdk_events; +pub mod search; mod sqlx; mod types; use api_event::metrics::{ApiEventMetric, ApiEventMetricRow}; @@ -664,3 +665,42 @@ pub struct ReportConfig { pub dispute_function: String, pub region: String, } + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(tag = "auth")] +#[serde(rename_all = "lowercase")] +pub enum OpensearchAuth { + Basic { username: String, password: String }, + Aws { region: String }, +} + +#[derive(Clone, Debug, serde::Deserialize)] +pub struct OpensearchIndexes { + pub payment_attempts: String, + pub payment_intents: String, + pub refunds: String, +} + +#[derive(Clone, Debug, serde::Deserialize)] +pub struct OpensearchConfig { + host: String, + auth: OpensearchAuth, + indexes: OpensearchIndexes, +} + +impl Default for OpensearchConfig { + fn default() -> Self { + Self { + host: "https://localhost:9200".to_string(), + auth: OpensearchAuth::Basic { + username: "admin".to_string(), + password: "admin".to_string(), + }, + indexes: OpensearchIndexes { + payment_attempts: "hyperswitch-payment-attempt-events".to_string(), + payment_intents: "hyperswitch-payment-intent-events".to_string(), + refunds: "hyperswitch-refund-events".to_string(), + }, + } + } +} diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs new file mode 100644 index 00000000000..8637c9d1105 --- /dev/null +++ b/crates/analytics/src/search.rs @@ -0,0 +1,150 @@ +use api_models::analytics::search::{ + GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput, + OpensearchOutput, SearchIndex, +}; +use aws_config::{self, meta::region::RegionProviderChain, Region}; +use common_utils::errors::CustomResult; +use opensearch::{ + auth::Credentials, + cert::CertificateValidation, + http::{ + request::JsonBody, + transport::{SingleNodeConnectionPool, TransportBuilder}, + Url, + }, + MsearchParts, OpenSearch, SearchParts, +}; +use serde_json::{json, Value}; +use strum::IntoEnumIterator; + +use crate::{errors::AnalyticsError, OpensearchAuth, OpensearchConfig, OpensearchIndexes}; + +#[derive(Debug, thiserror::Error)] +pub enum OpensearchError { + #[error("Opensearch connection error")] + ConnectionError, + #[error("Opensearch NON-200 response content: '{0}'")] + ResponseNotOK(String), + #[error("Opensearch response error")] + ResponseError, +} + +pub fn search_index_to_opensearch_index(index: SearchIndex, config: &OpensearchIndexes) -> String { + match index { + SearchIndex::PaymentAttempts => config.payment_attempts.clone(), + SearchIndex::PaymentIntents => config.payment_intents.clone(), + SearchIndex::Refunds => config.refunds.clone(), + } +} + +async fn get_opensearch_client(config: OpensearchConfig) -> Result<OpenSearch, OpensearchError> { + let url = Url::parse(&config.host).map_err(|_| OpensearchError::ConnectionError)?; + let transport = match config.auth { + OpensearchAuth::Basic { username, password } => { + let credentials = Credentials::Basic(username, password); + TransportBuilder::new(SingleNodeConnectionPool::new(url)) + .cert_validation(CertificateValidation::None) + .auth(credentials) + .build() + .map_err(|_| OpensearchError::ConnectionError)? + } + OpensearchAuth::Aws { region } => { + let region_provider = RegionProviderChain::first_try(Region::new(region)); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + let conn_pool = SingleNodeConnectionPool::new(url); + TransportBuilder::new(conn_pool) + .auth( + sdk_config + .clone() + .try_into() + .map_err(|_| OpensearchError::ConnectionError)?, + ) + .service_name("es") + .build() + .map_err(|_| OpensearchError::ConnectionError)? + } + }; + Ok(OpenSearch::new(transport)) +} + +pub async fn msearch_results( + req: GetGlobalSearchRequest, + merchant_id: &String, + config: OpensearchConfig, +) -> CustomResult<Vec<GetSearchResponse>, AnalyticsError> { + let client = get_opensearch_client(config.clone()) + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + let mut msearch_vector: Vec<JsonBody<Value>> = vec![]; + for index in SearchIndex::iter() { + msearch_vector + .push(json!({"index": search_index_to_opensearch_index(index,&config.indexes)}).into()); + msearch_vector.push(json!({"query": {"bool": {"must": {"query_string": {"query": req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}}).into()); + } + + let response = client + .msearch(MsearchParts::None) + .body(msearch_vector) + .send() + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + let response_body = response + .json::<OpenMsearchOutput<Value>>() + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + Ok(response_body + .responses + .into_iter() + .zip(SearchIndex::iter()) + .map(|(index_hit, index)| GetSearchResponse { + count: index_hit.hits.total.value, + index, + hits: index_hit + .hits + .hits + .into_iter() + .map(|hit| hit._source) + .collect(), + }) + .collect()) +} + +pub async fn search_results( + req: GetSearchRequestWithIndex, + merchant_id: &String, + config: OpensearchConfig, +) -> CustomResult<GetSearchResponse, AnalyticsError> { + let search_req = req.search_req; + + let client = get_opensearch_client(config.clone()) + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + let response = client + .search(SearchParts::Index(&[&search_index_to_opensearch_index(req.index.clone(),&config.indexes)])) + .from(search_req.offset) + .size(search_req.count) + .body(json!({"query": {"bool": {"must": {"query_string": {"query": search_req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}})) + .send() + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + let response_body = response + .json::<OpensearchOutput<Value>>() + .await + .map_err(|_| AnalyticsError::UnknownError)?; + + Ok(GetSearchResponse { + count: response_body.hits.total.value, + index: req.index, + hits: response_body + .hits + .hits + .into_iter() + .map(|hit| hit._source) + .collect(), + }) +} diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 1434c357798..ad035c707cc 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -19,6 +19,7 @@ pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; pub mod sdk_events; +pub mod search; #[derive(Debug, serde::Serialize)] pub struct NameDescription { @@ -251,7 +252,6 @@ pub struct GetApiEventMetricRequest { #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] - pub struct GetDisputeFilterRequest { pub time_range: TimeRange, #[serde(default)] diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs new file mode 100644 index 00000000000..07223c90660 --- /dev/null +++ b/crates/api_models/src/analytics/search.rs @@ -0,0 +1,73 @@ +use serde_json::Value; + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct SearchFilters { + pub payment_method: Option<Vec<String>>, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetGlobalSearchRequest { + pub query: String, + #[serde(default)] + pub filters: Option<SearchFilters>, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetSearchRequest { + pub offset: i64, + pub count: i64, + pub query: String, + #[serde(default)] + pub filters: Option<SearchFilters>, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetSearchRequestWithIndex { + pub index: SearchIndex, + pub search_req: GetSearchRequest, +} + +#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SearchIndex { + PaymentAttempts, + PaymentIntents, + Refunds, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetSearchResponse { + pub count: u64, + pub index: SearchIndex, + pub hits: Vec<Value>, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpenMsearchOutput<T> { + pub responses: Vec<OpensearchOutput<T>>, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchOutput<T> { + pub hits: OpensearchResults<T>, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchResults<T> { + pub total: OpensearchResultsTotal, + pub hits: Vec<OpensearchHits<T>>, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchResultsTotal { + pub value: u64, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchHits<T> { + pub _source: T, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 218881389db..46fa8caa6df 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -23,7 +23,7 @@ use crate::{ admin::*, analytics::{ api_event::*, connector_events::ConnectorEventsRequest, - outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, + outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, search::*, *, }, api_keys::*, cards_info::*, @@ -96,6 +96,10 @@ impl_misc_api_event_type!( ReportRequest, ConnectorEventsRequest, OutgoingWebhookLogsRequest, + GetGlobalSearchRequest, + GetSearchRequest, + GetSearchResponse, + GetSearchRequestWithIndex, GetDisputeFilterRequest, DisputeFiltersResponse, GetDisputeMetricRequest diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index f7bee88b8c3..a9c2b8995b5 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -8,6 +8,9 @@ pub mod routes { outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, }; use api_models::analytics::{ + search::{ + GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, + }, GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, GetDisputeMetricRequest, GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, @@ -89,6 +92,12 @@ pub mod routes { web::resource("metrics/api_events") .route(web::post().to(get_api_events_metrics)), ) + .service( + web::resource("search").route(web::post().to(get_global_search_results)), + ) + .service( + web::resource("search/{domain}").route(web::post().to(get_search_results)), + ) .service( web::resource("filters/disputes") .route(web::post().to(get_dispute_filters)), @@ -113,7 +122,7 @@ pub mod routes { state, &req, domain.into_inner(), - |_, _, domain| async { + |_, _, domain: analytics::AnalyticsDomain| async { analytics::core::get_domain_info(domain) .await .map(ApplicationResponse::Json) @@ -592,6 +601,63 @@ pub mod routes { .await } + pub async fn get_global_search_results( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetGlobalSearchRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetGlobalSearchResults; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + analytics::search::msearch_results( + req, + &auth.merchant_account.merchant_id, + state.conf.opensearch.clone(), + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_search_results( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetSearchRequest>, + index: actix_web::web::Path<SearchIndex>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSearchResults; + let indexed_req = GetSearchRequestWithIndex { + search_req: json_payload.into_inner(), + index: index.into_inner(), + }; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + indexed_req, + |state, auth: AuthenticationData, req| async move { + analytics::search::search_results( + req, + &auth.merchant_account.merchant_id, + state.conf.opensearch.clone(), + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index f89d1811988..6906b5a3e7a 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -350,6 +350,8 @@ pub(crate) async fn fetch_raw_secrets( payment_link: conf.payment_link, #[cfg(feature = "olap")] analytics, + #[cfg(feature = "olap")] + opensearch: conf.opensearch, #[cfg(feature = "kv_store")] kv_config: conf.kv_config, #[cfg(feature = "frm")] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index dc4826dfed6..2f87c5c21d7 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -4,7 +4,7 @@ use std::{ }; #[cfg(feature = "olap")] -use analytics::ReportConfig; +use analytics::{OpensearchConfig, ReportConfig}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; @@ -112,6 +112,8 @@ pub struct Settings<S: SecretState> { pub frm: Frm, #[cfg(feature = "olap")] pub report_download_config: ReportConfig, + #[cfg(feature = "olap")] + pub opensearch: OpensearchConfig, pub events: EventsConfig, #[cfg(feature = "olap")] pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index b68cdcc6fcc..5ad0f706706 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -54,6 +54,8 @@ pub enum AnalyticsFlow { GetApiEventFilters, GetConnectorEvents, GetOutgoingWebhookEvents, + GetGlobalSearchResults, + GetSearchResults, GetDisputeFilters, GetDisputeMetrics, }
2024-02-26T20:52:19Z
## Description Search APIs for dashboard global search ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Search APIs for dashboard global search ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
45ed56f16516c44acbe75b75c0621b78ccdb9894
[ "Cargo.lock", "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/analytics/Cargo.toml", "crates/analytics/src/lambda_utils.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/search.rs", "crates/api_models/sr...
juspay/hyperswitch
juspay__hyperswitch-3799
Bug: [BUG]: connector request is being built twice ### Bug Description When a payment is confirmed, the `connector_request` log is being printed twice ### Expected Behavior It should be printed only once ### Actual Behavior Two instances of the log line can be found ### Steps To Reproduce - Create a payment with `confirm` = `true` - Search for log with `connector_request` tag ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 1c4d1810c88..45decfd451d 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -338,30 +338,31 @@ where ], ); - let connector_request = connector_request.or(connector_integration - .build_request(req, &state.conf.connectors) - .map_err(|error| { - if matches!( - error.current_context(), - &errors::ConnectorError::RequestEncodingFailed - | &errors::ConnectorError::RequestEncodingFailedWithReason(_) - ) { - metrics::REQUEST_BUILD_FAILURE.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes( - "connector", - req.connector.to_string(), - )], - ) - } - error - })?); + let connector_request = match connector_request { + Some(connector_request) => Some(connector_request), + None => connector_integration + .build_request(req, &state.conf.connectors) + .map_err(|error| { + if matches!( + error.current_context(), + &errors::ConnectorError::RequestEncodingFailed + | &errors::ConnectorError::RequestEncodingFailedWithReason(_) + ) { + metrics::REQUEST_BUILD_FAILURE.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + req.connector.to_string(), + )], + ) + } + error + })?, + }; match connector_request { Some(request) => { - logger::debug!(connector_request=?request); - let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) @@ -1828,7 +1829,7 @@ pub fn build_redirection_form( threeDSsecureInterface.on('challenge', function(e) {{ console.log('Challenged'); - document.getElementById('loader-wrapper').style.display = 'none'; + document.getElementById('loader-wrapper').style.display = 'none'; }}); threeDSsecureInterface.on('complete', function(e) {{
2024-02-26T13:04:52Z
## Description <!-- Describe your changes in detail --> This PR fixes the duplicate request that was being constructed even if the connector_request already exists. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The `or()` function does eager evaluation. This means that even if there is Some(val) the part of code in the or part is evaluated. This is causing the request to be constructed twice. Fixes #3799 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Manual, compiler guided. - Create a payment and check if `connector_request` is logged only once.
75c633fc7c37341177597041ccbcdfc3cf9e236f
- Manual, compiler guided. - Create a payment and check if `connector_request` is logged only once.
[ "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3825
Bug: [FEATURE] : [Forte] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 83bcb2c551b..00efbefe287 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -240,7 +240,7 @@ pub enum ForteAction { #[derive(Debug, Deserialize, Serialize)] pub struct FortePaymentsResponse { pub transaction_id: String, - pub location_id: String, + pub location_id: Secret<String>, pub action: ForteAction, pub authorization_amount: Option<f64>, pub authorization_code: String, @@ -289,7 +289,7 @@ impl<F, T> #[derive(Debug, Deserialize, Serialize)] pub struct FortePaymentsSyncResponse { pub transaction_id: String, - pub location_id: String, + pub location_id: Secret<String>, pub status: FortePaymentStatus, pub action: ForteAction, pub authorization_amount: Option<f64>, @@ -434,7 +434,7 @@ pub struct CancelResponseStatus { #[derive(Debug, Deserialize, Serialize)] pub struct ForteCancelResponse { pub transaction_id: String, - pub location_id: String, + pub location_id: Secret<String>, pub action: String, pub authorization_code: String, pub entered_by: String,
2024-02-26T11:15:49Z
## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Forte. ## Test Case <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1.a.1 Card Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LQJkIZUCjJegIRLaclDqzXFZi5g76kp3AjfZ18bxUroPYL9iTNqSbMTiNkvzTO62' \ --data-raw '{ "amount": 2000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 1.a.2. Psync ``` curl --location 'http://localhost:8080/payments/pay_m55biPPvXK58EXXDzViv?expand_captures=true' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' ``` 1.b. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` masked_response should be ``` "masked_response":\"{\\\"transaction_id\\\":\\\"trn_2d204ee6-263a-4f4f-9a52-42f66b899583\\\",\\\"location_id\\\":\\\"*** alloc::string::String ***\\\",\\\"action\\\":\\\"sale\\\",\\\"authorization_amount\\\":20.0,\\\"authorization_code\\\":\\\"6QL672\\\",\\\"entered_by\\\":\\\"0ec774886e654a66c2e46854b0f4f002\\\",\\\"billing_address\\\":{\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\"},\\\"card\\\":{\\\"name_on_card\\\":\\\"*** alloc::string::String ***\\\",\\\"last_4_account_number\\\":\\\"1111\\\",\\\"masked_account_number\\\":\\\"****1111\\\",\\\"card_type\\\":\\\"visa\\\"},\\\"response\\\":{\\\"environment\\\":\\\"sandbox\\\",\\\"response_type\\\":\\\"A\\\",\\\"response_code\\\":\\\"A01\\\",\\\"response_desc\\\":\\\"TEST APPROVAL\\\",\\\"authorization_code\\\":\\\"6QL672\\\",\\\"avs_result\\\":\\\"Y\\\",\\\"cvv_result\\\":\\\"M\\\"}}\",\"error\":null,\"url\":\"https://sandbox.forte.net/api/v3/organizations/org_438530/locations/loc_316671/transactions\",\"method\":\"POST\",\"payment_id\":\"pay_weAKeLQvLWQuRZpDrV76\",\"merchant_id\":\"merchant_1708944415\",\"created_at\":1708945666007,\"request_id\":\"018de519-66d7-71ff-b05b-c50d3ac3b156\",\"latency\":1515,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201} ``` 2.a Void a transaction 2.a.1 Auth a transaction ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api-key}}' \ --data-raw '{ "amount": 2000, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 2.a.2 Void the payment ``` curl --location 'http://localhost:8080/payments/pay_m55biPPvXK58EXXDzViv/cancel' \ --header 'Content-Type: application/json' \ --header 'api-key:{{api_key}}' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` 1.b. Check if all the sensitive data in the `masked_response` is masked. In logs check for `topic = "hyperswitch-outgoing-connector-events" ` ## Impacted Area > Card Payment > Payment Sync > Payment Cancel
75c633fc7c37341177597041ccbcdfc3cf9e236f
[ "crates/router/src/connector/forte/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3823
Bug: [FIX] add unit tests to check backwards compatibility of KV types
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 927a05bfa56..cc4f3e5a89a 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -776,3 +776,100 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { } } } + +mod tests { + + #[test] + fn test_backwards_compatibility() { + let serialized_payment_attempt = r#"{ + "id": 1, + "payment_id": "PMT123456789", + "merchant_id": "M123456789", + "attempt_id": "ATMPT123456789", + "status": "pending", + "amount": 10000, + "currency": "USD", + "save_to_locker": true, + "connector": "stripe", + "error_message": null, + "offer_amount": 9500, + "surcharge_amount": 500, + "tax_amount": 800, + "payment_method_id": "CRD123456789", + "payment_method": "card", + "connector_transaction_id": "CNTR123456789", + "capture_method": "automatic", + "capture_on": "2022-09-10T10:11:12Z", + "confirm": false, + "authentication_type": "no_three_ds", + "created_at": "2024-02-26T12:00:00Z", + "modified_at": "2024-02-26T12:00:00Z", + "last_synced": null, + "cancellation_reason": null, + "amount_to_capture": 10000, + "mandate_id": null, + "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" + }, + "error_code": null, + "payment_token": "TOKEN123456789", + "connector_metadata": null, + "payment_experience": "redirect_to_url", + "payment_method_type": "credit", + "payment_method_data": { + "card": { + "card_number": "4242424242424242", + "card_exp_month": "10", + "card_cvc": "123", + "card_exp_year": "2024", + "card_holder_name": "John Doe" + } + }, + "business_sub_label": "Premium", + "straight_through_algorithm": null, + "preprocessing_step_id": null, + "mandate_details": null, + "error_reason": null, + "multiple_capture_count": 0, + "connector_response_reference_id": null, + "amount_capturable": 10000, + "updated_by": "redis_kv", + "merchant_connector_id": "MCN123456789", + "authentication_data": null, + "encoded_data": null, + "unified_code": null, + "unified_message": null, + "net_amount": 10200, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "single_use": { + "amount": 6540, + "currency": "USD" + } + } +}, + "fingerprint_id": null +}"#; + let deserialized = + serde_json::from_str::<super::PaymentAttempt>(serialized_payment_attempt); + + assert!(deserialized.is_ok()); + } +} diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 69fb61a8d42..b14554e3032 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -485,3 +485,56 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } } } + +mod tests { + #[test] + fn test_backwards_compatibility() { + let serialized_payment_intent = r#"{ + "id": 123, + "payment_id": "payment_12345", + "merchant_id": "merchant_67890", + "status": "succeeded", + "amount": 10000, + "currency": "USD", + "amount_captured": null, + "customer_id": "cust_123456", + "description": "Test Payment", + "return_url": "https://example.com/return", + "metadata": null, + "connector_id": "connector_001", + "shipping_address_id": null, + "billing_address_id": null, + "statement_descriptor_name": null, + "statement_descriptor_suffix": null, + "created_at": "2024-02-01T12:00:00Z", + "modified_at": "2024-02-01T12:00:00Z", + "last_synced": null, + "setup_future_usage": null, + "off_session": null, + "client_secret": "sec_abcdef1234567890", + "active_attempt_id": "attempt_123", + "business_country": "US", + "business_label": null, + "order_details": null, + "allowed_payment_method_types": "credit", + "connector_metadata": null, + "feature_metadata": null, + "attempt_count": 1, + "profile_id": null, + "merchant_decision": null, + "payment_link_id": null, + "payment_confirm_source": null, + "updated_by": "admin", + "surcharge_applicable": null, + "request_incremental_authorization": null, + "incremental_authorization_allowed": null, + "authorization_count": null, + "session_expiry": null, + "fingerprint_id": null +}"#; + let deserialized_payment_intent = + serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); + + assert!(deserialized_payment_intent.is_ok()); + } +} diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index bb805fb646c..0ee486bae48 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -244,3 +244,41 @@ impl common_utils::events::ApiEventMetric for Refund { }) } } + +mod tests { + #[test] + fn test_backwards_compatibility() { + let serialized_refund = r#"{ + "id": 1, + "internal_reference_id": "internal_ref_123", + "refund_id": "refund_456", + "payment_id": "payment_789", + "merchant_id": "merchant_123", + "connector_transaction_id": "connector_txn_789", + "connector": "stripe", + "connector_refund_id": null, + "external_reference_id": null, + "refund_type": "instant_refund", + "total_amount": 10000, + "currency": "USD", + "refund_amount": 9500, + "refund_status": "Success", + "sent_to_gateway": true, + "refund_error_message": null, + "metadata": null, + "refund_arn": null, + "created_at": "2024-02-26T12:00:00Z", + "updated_at": "2024-02-26T12:00:00Z", + "description": null, + "attempt_id": "attempt_123", + "refund_reason": null, + "refund_error_code": null, + "profile_id": null, + "updated_by": "admin", + "merchant_connector_id": null +}"#; + let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); + + assert!(deserialized.is_ok()); + } +}
2024-02-26T10:51:09Z
## Description <!-- Describe your changes in detail --> Add Unit tests for testing backwards compatibility ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This tests if the type is backwards compatible or not ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Local Testing - Run `cargo tests --all-features -p diesel_models` it should pass all tests ## Sandbox - Cannot be tested in sandbox
75c633fc7c37341177597041ccbcdfc3cf9e236f
[ "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/payment_intent.rs", "crates/diesel_models/src/refund.rs" ]