hash
stringlengths
40
40
date
stringdate
2022-11-17 13:04:47
2025-03-21 17:04:41
author
stringclasses
141 values
commit_message
stringlengths
22
166
is_merge
bool
1 class
git_diff
stringlengths
238
9.63M
type
stringclasses
17 values
masked_commit_message
stringlengths
6
143
c38485ad28927a41009a32b77b201bd12db4dc77
2023-08-25 01:48:06
Sanchith Hegde
ci: use Rust stable from 2 weeks ago (#2012)
false
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml index 61aaf5951f2..a51ef804dae 100644 --- a/.github/workflows/CI-pr.yml +++ b/.github/workflows/CI-pr.yml @@ -290,7 +290,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago components: clippy - name: Install cargo-hack diff --git a/.github/workflows/CI-push.yml b/.github/workflows/CI-push.yml index aea0aea6566..653905975bb 100644 --- a/.github/workflows/CI-push.yml +++ b/.github/workflows/CI-push.yml @@ -131,7 +131,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago components: clippy - name: Install cargo-hack diff --git a/.github/workflows/connector-sanity-tests.yml b/.github/workflows/connector-sanity-tests.yml index 4d6199a86d3..40a3c361250 100644 --- a/.github/workflows/connector-sanity-tests.yml +++ b/.github/workflows/connector-sanity-tests.yml @@ -84,7 +84,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - uses: Swatinem/[email protected] diff --git a/.github/workflows/conventional-commit-check.yml b/.github/workflows/conventional-commit-check.yml index 174287c61ce..c02d8a3bfb4 100644 --- a/.github/workflows/conventional-commit-check.yml +++ b/.github/workflows/conventional-commit-check.yml @@ -43,7 +43,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - uses: baptiste0928/[email protected] with: diff --git a/.github/workflows/migration-check.yaml b/.github/workflows/migration-check.yaml index 57d1f579da2..0c4baaa9619 100644 --- a/.github/workflows/migration-check.yaml +++ b/.github/workflows/migration-check.yaml @@ -45,7 +45,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - uses: baptiste0928/[email protected] with: diff --git a/.github/workflows/postman-collection-runner.yml b/.github/workflows/postman-collection-runner.yml index c6e0f0f57f2..316c9891253 100644 --- a/.github/workflows/postman-collection-runner.yml +++ b/.github/workflows/postman-collection-runner.yml @@ -77,7 +77,7 @@ jobs: if: ${{ ((github.event_name == 'pull_request') && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name)) || (github.event_name == 'merge_group')}} uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - name: Build and Cache Rust Dependencies if: ${{ ((github.event_name == 'pull_request') && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name)) || (github.event_name == 'merge_group')}} diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml index e42e0dd266b..8bd80ee1508 100644 --- a/.github/workflows/release-new-version.yml +++ b/.github/workflows/release-new-version.yml @@ -32,7 +32,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - name: Install cocogitto uses: baptiste0928/[email protected] diff --git a/.github/workflows/validate-openapi-spec.yml b/.github/workflows/validate-openapi-spec.yml index 72b76157f10..5c4c28518e6 100644 --- a/.github/workflows/validate-openapi-spec.yml +++ b/.github/workflows/validate-openapi-spec.yml @@ -33,7 +33,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: stable 2 weeks ago - name: Generate the OpenAPI spec file shell: bash diff --git a/Cargo.lock b/Cargo.lock index ce46b6c6e95..1eb250514f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1644,6 +1644,22 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data_models" +version = "0.1.0" +dependencies = [ + "api_models", + "async-trait", + "common_enums", + "common_utils", + "error-stack", + "serde", + "serde_json", + "strum 0.25.0", + "thiserror", + "time 0.3.22", +] + [[package]] name = "deadpool" version = "0.9.5" @@ -1824,9 +1840,9 @@ dependencies = [ [[package]] name = "dyn-clone" -version = "1.0.11" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b0cf012f1230e43cd00ebb729c6bb58707ecfa8ad08b52ef3a4ccd2697fc30" +checksum = "bbfc4744c1b8f2a09adc0e55242f60b1af195d88596bd8700be74418c056c555" [[package]] name = "either" @@ -2998,9 +3014,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206bf83f415b0579fd885fe0804eb828e727636657dc1bf73d80d2f1218e14a1" +checksum = "fa6e72583bf6830c956235bff0d5afec8cf2952f579ebad18ae7821a917d950f" dependencies = [ "async-io", "async-lock", @@ -3968,7 +3984,7 @@ dependencies = [ "clap", "common_utils", "config", - "crc32fast", + "data_models", "derive_deref", "diesel", "diesel_models", @@ -3988,7 +4004,6 @@ dependencies = [ "maud", "mimalloc", "mime", - "moka", "nanoid", "num_cpus", "once_cell", @@ -4588,11 +4603,24 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" name = "storage_impl" version = "0.1.0" dependencies = [ + "api_models", "async-bb8-diesel", "async-trait", "bb8", + "common_utils", + "crc32fast", + "data_models", "diesel", + "diesel_models", + "dyn-clone", + "error-stack", + "futures", "masking", + "moka", + "once_cell", + "redis_interface", + "router_env", + "tokio", ] [[package]] diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index bf95efe64fd..7a7bc9d8910 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -10163,11 +10163,6 @@ "format": "int64", "description": "The total number of refunds in the list" }, - "total_count": { - "type": "integer", - "format": "int64", - "description": "The total number of refunds in the list" - }, "data": { "type": "array", "items": {
ci
use Rust stable from 2 weeks ago (#2012)
9baa1ef65442c11dc57dd4b82a32c93f9542d45d
2024-11-26 13:50:33
Gnanasundari24
ci(cypress): Add list and revoke for zero auth mandate payments (#6569)
false
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js index 9091135d539..f341db19f6c 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js @@ -4,7 +4,7 @@ import getConnectorDetails, * as utils from "../PaymentUtils/Utils"; let globalState; -describe("Card - SingleUse Mandates flow test", () => { +describe("Card - List and revoke Mandates flow test", () => { before("seed global state", () => { cy.task("getGlobalState").then((state) => { globalState = new State(state); @@ -71,4 +71,55 @@ describe("Card - SingleUse Mandates flow test", () => { }); } ); + context("Card - Zero auth CIT and MIT payment flow test", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "ZeroAuthMandate" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.citForMandatesCallTest( + fixtures.citConfirmBody, + req_data, + res_data, + 0, + true, + "automatic", + "setup_mandate", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("list-mandate-call-test", () => { + cy.listMandateCallTest(globalState); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + fixtures.mitConfirmBody, + 7000, + true, + "automatic", + globalState + ); + }); + + it("list-mandate-call-test", () => { + cy.listMandateCallTest(globalState); + }); + + it("revoke-mandate-call-test", () => { + cy.revokeMandateCallTest(globalState); + }); + }); }); diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index 5ed6617ae42..3df6c901d97 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -1969,9 +1969,7 @@ Cypress.Commands.add( } else if (response.body.authentication_type === "no_three_ds") { if (response.body.connector === "fiuu") { expect(response.body.status).to.equal("failed"); - } else { - expect(response.body.status).to.equal("succeeded"); - } + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}` @@ -2051,9 +2049,7 @@ Cypress.Commands.add( } else if (response.body.authentication_type === "no_three_ds") { if (response.body.connector === "fiuu") { expect(response.body.status).to.equal("failed"); - } else { - expect(response.body.status).to.equal("succeeded"); - } + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}`
ci
Add list and revoke for zero auth mandate payments (#6569)
aab8f6035c16ca19009f8f1e0db688c17bc0b2b6
2023-11-09 11:57:13
harsh-sharma-juspay
fix(analytics): added hs latency to api event for paymentconfirm call (#2787)
false
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 2fcd792eca8..c6252982638 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -346,7 +346,7 @@ pub fn payments_to_payments_response<R, Op, F: Clone>( connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, - is_latency_header_enabled: Option<bool>, + _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, @@ -451,13 +451,13 @@ where payment_confirm_source.to_string(), )) } - if Some(true) == is_latency_header_enabled { - headers.extend( - external_latency - .map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())]) - .unwrap_or_default(), - ); - } + + headers.extend( + external_latency + .map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())]) + .unwrap_or_default(), + ); + let output = Ok(match payment_request { Some(_request) => { if payments::is_start_pay(&operation)
fix
added hs latency to api event for paymentconfirm call (#2787)
6cf8f0582cfa4f6a58c67a868cb67846970b3835
2023-10-18 16:54:56
Swangi Kumari
feat(Connector): [Paypal] add support for dispute webhooks for paypal connector (#2353)
false
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index df5bfc44d85..120795bef9c 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -8,7 +8,7 @@ use error_stack::{IntoReport, ResultExt}; use masking::PeekInterface; use transformers as paypal; -use self::transformers::{PaypalAuthResponse, PaypalMeta}; +use self::transformers::{PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType}; use super::utils::PaymentsCompleteAuthorizeRequestData; use crate::{ configs::settings, @@ -30,6 +30,7 @@ use crate::{ types::{ self, api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource}, + transformers::ForeignFrom, ErrorResponse, Response, }, utils::{self, BytesExt}, @@ -1113,6 +1114,17 @@ impl api::IncomingWebhook for Paypal { api_models::webhooks::RefundIdType::ConnectorRefundId(resource.id), )) } + paypal::PaypalResource::PaypalDisputeWebhooks(resource) => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId( + resource + .dispute_transactions + .first() + .map(|transaction| transaction.reference_id.clone()) + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )) + } } } @@ -1124,7 +1136,33 @@ impl api::IncomingWebhook for Paypal { .body .parse_struct("PaypalWebooksEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(payload.event_type)) + let outcome = match payload.event_type { + PaypalWebhookEventType::CustomerDisputeCreated + | PaypalWebhookEventType::CustomerDisputeResolved + | PaypalWebhookEventType::CustomerDisputedUpdated + | PaypalWebhookEventType::RiskDisputeCreated => Some( + request + .body + .parse_struct::<paypal::DisputeOutcome>("PaypalWebooksEventType") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)? + .outcome_code, + ), + PaypalWebhookEventType::PaymentAuthorizationCreated + | PaypalWebhookEventType::PaymentAuthorizationVoided + | PaypalWebhookEventType::PaymentCaptureDeclined + | PaypalWebhookEventType::PaymentCaptureCompleted + | PaypalWebhookEventType::PaymentCapturePending + | PaypalWebhookEventType::PaymentCaptureRefunded + | PaypalWebhookEventType::CheckoutOrderApproved + | PaypalWebhookEventType::CheckoutOrderCompleted + | PaypalWebhookEventType::CheckoutOrderProcessed + | PaypalWebhookEventType::Unknown => None, + }; + + Ok(api::IncomingWebhookEvent::foreign_from(( + payload.event_type, + outcome, + ))) } fn get_webhook_resource_object( @@ -1152,9 +1190,39 @@ impl api::IncomingWebhook for Paypal { ) .into_report() .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?, + paypal::PaypalResource::PaypalDisputeWebhooks(_) => serde_json::to_value(details) + .into_report() + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?, }; Ok(sync_payload) } + + fn get_dispute_details( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + let payload: paypal::PaypalDisputeWebhooks = request + .body + .parse_struct("PaypalDisputeWebhooks") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api::disputes::DisputePayload { + amount: connector_utils::to_currency_lower_unit( + payload.dispute_amount.value, + payload.dispute_amount.currency_code, + )?, + currency: payload.dispute_amount.currency_code.to_string(), + dispute_stage: api_models::enums::DisputeStage::from( + payload.dispute_life_cycle_stage.clone(), + ), + connector_status: payload.status.to_string(), + connector_dispute_id: payload.dispute_id, + connector_reason: payload.reason, + connector_reason_code: payload.external_reason_code, + challenge_required_by: payload.seller_response_due_date, + created_at: payload.create_time, + updated_at: payload.update_time, + }) + } } impl services::ConnectorRedirectResponse for Paypal { diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 927c33277ab..0092363523e 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1,8 +1,9 @@ -use api_models::payments::BankRedirectData; +use api_models::{enums, payments::BankRedirectData}; use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use url::Url; use crate::{ @@ -67,8 +68,8 @@ pub enum PaypalPaymentIntent { #[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)] pub struct OrderAmount { - currency_code: storage_enums::Currency, - value: String, + pub currency_code: storage_enums::Currency, + pub value: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -1403,7 +1404,7 @@ pub struct PaypalWebhooksBody { pub resource: PaypalResource, } -#[derive(Deserialize, Debug, Serialize)] +#[derive(Clone, Deserialize, Debug, strum::Display, Serialize)] pub enum PaypalWebhookEventType { #[serde(rename = "PAYMENT.AUTHORIZATION.CREATED")] PaymentAuthorizationCreated, @@ -1423,6 +1424,14 @@ pub enum PaypalWebhookEventType { CheckoutOrderCompleted, #[serde(rename = "CHECKOUT.ORDER.PROCESSED")] CheckoutOrderProcessed, + #[serde(rename = "CUSTOMER.DISPUTE.CREATED")] + CustomerDisputeCreated, + #[serde(rename = "CUSTOMER.DISPUTE.RESOLVED")] + CustomerDisputeResolved, + #[serde(rename = "CUSTOMER.DISPUTE.UPDATED")] + CustomerDisputedUpdated, + #[serde(rename = "RISK.DISPUTE.CREATED")] + RiskDisputeCreated, #[serde(other)] Unknown, } @@ -1433,6 +1442,64 @@ pub enum PaypalResource { PaypalCardWebhooks(Box<PaypalCardWebhooks>), PaypalRedirectsWebhooks(Box<PaypalRedirectsWebhooks>), PaypalRefundWebhooks(Box<PaypalRefundWebhooks>), + PaypalDisputeWebhooks(Box<PaypalDisputeWebhooks>), +} + +#[derive(Deserialize, Debug, Serialize)] +pub struct PaypalDisputeWebhooks { + pub dispute_id: String, + pub dispute_transactions: Vec<DisputeTransaction>, + pub dispute_amount: OrderAmount, + pub dispute_outcome: DisputeOutcome, + pub dispute_life_cycle_stage: DisputeLifeCycleStage, + pub status: DisputeStatus, + pub reason: Option<String>, + pub external_reason_code: Option<String>, + pub seller_response_due_date: Option<PrimitiveDateTime>, + pub update_time: Option<PrimitiveDateTime>, + pub create_time: Option<PrimitiveDateTime>, +} + +#[derive(Deserialize, Debug, Serialize)] +pub struct DisputeTransaction { + pub reference_id: String, +} + +#[derive(Clone, Deserialize, Debug, strum::Display, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DisputeLifeCycleStage { + Inquiry, + Chargeback, + PreArbitration, + Arbitration, +} + +#[derive(Deserialize, Debug, strum::Display, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DisputeStatus { + Open, + WaitingForBuyerResponse, + WaitingForSellerResponse, + UnderReview, + Resolved, + Other, +} + +#[derive(Deserialize, Debug, Serialize)] +pub struct DisputeOutcome { + pub outcome_code: OutcomeCode, +} + +#[derive(Deserialize, Debug, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum OutcomeCode { + ResolvedBuyerFavour, + ResolvedSellerFavour, + ResolvedWithPayout, + CanceledByBuyer, + ACCEPTED, + DENIED, + NONE, } #[derive(Deserialize, Debug, Serialize)] @@ -1482,8 +1549,8 @@ pub struct PaypalWebooksEventType { pub event_type: PaypalWebhookEventType, } -impl From<PaypalWebhookEventType> for api::IncomingWebhookEvent { - fn from(event: PaypalWebhookEventType) -> Self { +impl ForeignFrom<(PaypalWebhookEventType, Option<OutcomeCode>)> for api::IncomingWebhookEvent { + fn foreign_from((event, outcome): (PaypalWebhookEventType, Option<OutcomeCode>)) -> Self { match event { PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::CheckoutOrderCompleted => Self::PaymentIntentSuccess, @@ -1491,14 +1558,49 @@ impl From<PaypalWebhookEventType> for api::IncomingWebhookEvent { | PaypalWebhookEventType::CheckoutOrderProcessed => Self::PaymentIntentProcessing, PaypalWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentFailure, PaypalWebhookEventType::PaymentCaptureRefunded => Self::RefundSuccess, + PaypalWebhookEventType::CustomerDisputeCreated => Self::DisputeOpened, + PaypalWebhookEventType::RiskDisputeCreated => Self::DisputeAccepted, + PaypalWebhookEventType::CustomerDisputeResolved => { + if let Some(outcome_code) = outcome { + Self::from(outcome_code) + } else { + Self::EventNotSupported + } + } PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::CheckoutOrderApproved + | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::Unknown => Self::EventNotSupported, } } } +impl From<OutcomeCode> for api::IncomingWebhookEvent { + fn from(outcome_code: OutcomeCode) -> Self { + match outcome_code { + OutcomeCode::ResolvedBuyerFavour => Self::DisputeLost, + OutcomeCode::ResolvedSellerFavour => Self::DisputeWon, + OutcomeCode::CanceledByBuyer => Self::DisputeCancelled, + OutcomeCode::ACCEPTED => Self::DisputeAccepted, + OutcomeCode::DENIED => Self::DisputeCancelled, + OutcomeCode::NONE => Self::DisputeCancelled, + OutcomeCode::ResolvedWithPayout => Self::EventNotSupported, + } + } +} + +impl From<DisputeLifeCycleStage> for enums::DisputeStage { + fn from(dispute_life_cycle_stage: DisputeLifeCycleStage) -> Self { + match dispute_life_cycle_stage { + DisputeLifeCycleStage::Inquiry => Self::PreDispute, + DisputeLifeCycleStage::Chargeback => Self::Dispute, + DisputeLifeCycleStage::PreArbitration => Self::PreArbitration, + DisputeLifeCycleStage::Arbitration => Self::PreArbitration, + } + } +} + #[derive(Deserialize, Serialize, Debug)] pub struct PaypalSourceVerificationRequest { pub transmission_id: String, @@ -1617,7 +1719,11 @@ impl TryFrom<PaypalWebhookEventType> for PaypalPaymentStatus { | PaypalWebhookEventType::CheckoutOrderProcessed => Ok(Self::Pending), PaypalWebhookEventType::PaymentAuthorizationCreated => Ok(Self::Created), PaypalWebhookEventType::PaymentCaptureRefunded => Ok(Self::Refunded), - PaypalWebhookEventType::Unknown => { + PaypalWebhookEventType::CustomerDisputeCreated + | PaypalWebhookEventType::CustomerDisputeResolved + | PaypalWebhookEventType::CustomerDisputedUpdated + | PaypalWebhookEventType::RiskDisputeCreated + | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } @@ -1637,6 +1743,10 @@ impl TryFrom<PaypalWebhookEventType> for RefundStatus { | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CheckoutOrderCompleted | PaypalWebhookEventType::CheckoutOrderProcessed + | PaypalWebhookEventType::CustomerDisputeCreated + | PaypalWebhookEventType::CustomerDisputeResolved + | PaypalWebhookEventType::CustomerDisputedUpdated + | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } @@ -1657,6 +1767,10 @@ impl TryFrom<PaypalWebhookEventType> for PaypalOrderStatus { PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureRefunded + | PaypalWebhookEventType::CustomerDisputeCreated + | PaypalWebhookEventType::CustomerDisputeResolved + | PaypalWebhookEventType::CustomerDisputedUpdated + | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) }
feat
[Paypal] add support for dispute webhooks for paypal connector (#2353)
fa7601c46dcef9421e02ef9f9536f05052323485
2024-05-14 05:44:42
github-actions
chore(version): 2024.05.14.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index f2532170a61..824fbcf3a15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,32 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.05.14.0 + +### Features + +- **connector:** Generate connector template code for gpayments authenticaition connector ([#4584](https://github.com/juspay/hyperswitch/pull/4584)) ([`2a302eb`](https://github.com/juspay/hyperswitch/commit/2a302eb5973c64d8b77f8110fdbeb536ccbe1488)) +- **payment_methods:** Pass `required_billing_contact_fields` field in `/session` call based on dynamic fields ([#4601](https://github.com/juspay/hyperswitch/pull/4601)) ([`348cd74`](https://github.com/juspay/hyperswitch/commit/348cd744dca20c54c6ed47c8036f43f16429c8f3)) +- **payments_update:** Update payment_method_billing in payment update ([#4614](https://github.com/juspay/hyperswitch/pull/4614)) ([`2692995`](https://github.com/juspay/hyperswitch/commit/26929956172e9f0e1e3fb41f5e4dbb19d866abf2)) +- **refunds:** Update refunds filters ([#4409](https://github.com/juspay/hyperswitch/pull/4409)) ([`cfab2af`](https://github.com/juspay/hyperswitch/commit/cfab2af7d4a2478d7609a1bd34dd0579dad194c2)) + +### Bug Fixes + +- **connector_token:** Move config redis ([#4540](https://github.com/juspay/hyperswitch/pull/4540)) ([`1602eb5`](https://github.com/juspay/hyperswitch/commit/1602eb541d317d9b155cbcbffed3d54f7d0b5acd)) + +### Refactors + +- **bank-transfer:** Remove billing from banktransfer payment data ([#4377](https://github.com/juspay/hyperswitch/pull/4377)) ([`0f5a370`](https://github.com/juspay/hyperswitch/commit/0f5a370b55140fd63aeab4ca8427bd371f5e5ec4)) +- **card_details:** Added missing card data fields for connectors ([#4571](https://github.com/juspay/hyperswitch/pull/4571)) ([`41655ba`](https://github.com/juspay/hyperswitch/commit/41655ba300567455a5b28b85584d990981a24167)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`22210b0`](https://github.com/juspay/hyperswitch/commit/22210b0ff44014b885842c804879267d9a83ab1b)) + +**Full Changelog:** [`2024.05.13.0...2024.05.14.0`](https://github.com/juspay/hyperswitch/compare/2024.05.13.0...2024.05.14.0) + +- - - + ## 2024.05.13.0 ### Features
chore
2024.05.14.0
2a53f52f994ca98a31509f05e31b3874b88d15bf
2024-10-15 05:55:27
github-actions
chore(version): 2024.10.15.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 31839725840..5beb943a8ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.10.15.0 + +### Features + +- **analytics:** Add metrics, filters and APIs for Analytics v2 Dashboard - Payments Page ([#5870](https://github.com/juspay/hyperswitch/pull/5870)) ([`f123df9`](https://github.com/juspay/hyperswitch/commit/f123df9aa31c45b417224af73c2a98325984b3dd)) +- **connector:** [CYBERSOURCE] Add paze dashboard configs ([#6304](https://github.com/juspay/hyperswitch/pull/6304)) ([`df280f2`](https://github.com/juspay/hyperswitch/commit/df280f2574ac701a5e32b9bcae90c87cab7bc5aa)) +- **payment_methods_v2:** Delete payment method api ([#6211](https://github.com/juspay/hyperswitch/pull/6211)) ([`8e538cd`](https://github.com/juspay/hyperswitch/commit/8e538cd6b3da4a155c55ce153982bff3c59ef575)) +- **payments:** Support for card_network filter in payments list ([#5994](https://github.com/juspay/hyperswitch/pull/5994)) ([`1ac8c92`](https://github.com/juspay/hyperswitch/commit/1ac8c92c4bd2259cdd8bf755210bcb3c0eb31472)) +- **router:** Add support for Samsung pay app tokens flow ([#6257](https://github.com/juspay/hyperswitch/pull/6257)) ([`f6b0b98`](https://github.com/juspay/hyperswitch/commit/f6b0b98e0a6c07308b481715f7c9ad063a5f0de9)) + +### Bug Fixes + +- **router:** + - Update nick_name only if card_token.card_holder_name is non empty and populate additional card_details from payment_attempt if not present in the locker ([#6308](https://github.com/juspay/hyperswitch/pull/6308)) ([`9da9c5e`](https://github.com/juspay/hyperswitch/commit/9da9c5e0ffe219a0bf6e08281b87c77eeb5c4575)) + - Replace underscore by hyphen in Samsung pay session call ([#6311](https://github.com/juspay/hyperswitch/pull/6311)) ([`7f1bbbf`](https://github.com/juspay/hyperswitch/commit/7f1bbbfffecb74555756b0003d6a0ae940e581db)) + +### Refactors + +- **connector:** [Adyen platform] api contract change for webhook ([#6281](https://github.com/juspay/hyperswitch/pull/6281)) ([`5b4a1d5`](https://github.com/juspay/hyperswitch/commit/5b4a1d5f6d7b4143116c5f1faf6cb325e4368e6d)) +- Add user agent header in outgoing webhooks ([#6289](https://github.com/juspay/hyperswitch/pull/6289)) ([`fe62b1f`](https://github.com/juspay/hyperswitch/commit/fe62b1fe2137de456a6a0e8e315fd0592c29577d)) + +### Documentation + +- **v2:** Added 'X-Merchant-Id' to headers in Profile API docs ([#6291](https://github.com/juspay/hyperswitch/pull/6291)) ([`ca086d0`](https://github.com/juspay/hyperswitch/commit/ca086d0b25ee12419ebcb7250b4a6678cc33a8a6)) + +**Full Changelog:** [`2024.10.11.0...2024.10.15.0`](https://github.com/juspay/hyperswitch/compare/2024.10.11.0...2024.10.15.0) + +- - - + ## 2024.10.11.0 ### Features
chore
2024.10.15.0
683c1b81c5a30ac0df93664805b78a8e44d49acc
2024-02-06 11:24:43
Tejas Mate
feat(connect): [NMI] Use connector_response_reference_id as reference to merchant (#2702)
false
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 9dce4960f3a..f7fc0c0a4f3 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -719,7 +719,7 @@ impl<T> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None, @@ -775,7 +775,7 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None, @@ -825,7 +825,7 @@ impl<T> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None,
feat
[NMI] Use connector_response_reference_id as reference to merchant (#2702)
6aec168b4f665e980dc989eb4c7f44eaad64f512
2023-10-04 20:01:57
github-actions
chore(version): v1.50.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8924ba3ecc1..d7070c21e93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.50.0 (2023-10-04) + +### Features + +- **connector:** + - [Stax] Use connector_response_reference_id as reference to merchant ([#2415](https://github.com/juspay/hyperswitch/pull/2415)) ([`099b241`](https://github.com/juspay/hyperswitch/commit/099b241096c69879a805ca81b1c5a23118e10b52)) + - [PowerTranz] Use connector_response_reference_id as reference to merchant ([#2413](https://github.com/juspay/hyperswitch/pull/2413)) ([`0d703c7`](https://github.com/juspay/hyperswitch/commit/0d703c7ab85c68f433767a70a0feabe8daa4f24c)) + - [Payeezy] Use connector_response_reference_id as reference to merchant ([#2410](https://github.com/juspay/hyperswitch/pull/2410)) ([`485c09d`](https://github.com/juspay/hyperswitch/commit/485c09d16743d73b446d6313f0ee6462c8a77028)) + - [Square] Use reference_id as reference to merchant ([#2434](https://github.com/juspay/hyperswitch/pull/2434)) ([`591c9b7`](https://github.com/juspay/hyperswitch/commit/591c9b70d9b7f8df5d7f5d2cb2d19cfaa1457fe1)) +- **router:** + - Remove unnecessary lookups in refund and payment_attempt kv flow ([#2425](https://github.com/juspay/hyperswitch/pull/2425)) ([`f720aec`](https://github.com/juspay/hyperswitch/commit/f720aecf1fb676cec71e636b877a46f9791d713a)) + - [OpenNode] response reference id ([#2416](https://github.com/juspay/hyperswitch/pull/2416)) ([`3bfea72`](https://github.com/juspay/hyperswitch/commit/3bfea72df34f4ce0ffdb61e49960fdf09b96eb5a)) + - Add profile id and extra filters in lists ([#2379](https://github.com/juspay/hyperswitch/pull/2379)) ([`ab2cde7`](https://github.com/juspay/hyperswitch/commit/ab2cde799371a66eb045cf8b20431b3b108dac44)) + +### Bug Fixes + +- **CI:** Fix spell check for CI pull request ([#2439](https://github.com/juspay/hyperswitch/pull/2439)) ([`04f2e11`](https://github.com/juspay/hyperswitch/commit/04f2e11cd4f3fd327408cddec36ccf4fb486b935)) +- **router:** Merchant account delete does not delete the merchant_key_store ([#2367](https://github.com/juspay/hyperswitch/pull/2367)) ([`35f7ce0`](https://github.com/juspay/hyperswitch/commit/35f7ce0f4d9e16184e2bb94360d3ced60f8b5af2)) + +### Refactors + +- **config:** Update payment method filter for apple pay ([#2423](https://github.com/juspay/hyperswitch/pull/2423)) ([`d177b4d`](https://github.com/juspay/hyperswitch/commit/d177b4d94f08fb8ef44b5c07ec1bdc771baa016d)) +- **payment_methods:** Add `requires_cvv` config while creating merchant account ([#2431](https://github.com/juspay/hyperswitch/pull/2431)) ([`6e5ab0d`](https://github.com/juspay/hyperswitch/commit/6e5ab0d121d6345f18bccc7f917064caa2737475)) +- **webhook:** Add a function to retrieve payment_id ([#2447](https://github.com/juspay/hyperswitch/pull/2447)) ([`409913f`](https://github.com/juspay/hyperswitch/commit/409913fd75076e4ee1dac1e4dc5b2f164528bc23)) + +### Build System / Dependencies + +- **deps:** Address `undeclared crate or module` errors on Windows for `scheduler` crate ([#2411](https://github.com/juspay/hyperswitch/pull/2411)) ([`4225238`](https://github.com/juspay/hyperswitch/commit/422523848e6516643a6beef1ba15af4e967f0c5b)) + +**Full Changelog:** [`v1.49.0...v1.50.0`](https://github.com/juspay/hyperswitch/compare/v1.49.0...v1.50.0) + +- - - + + ## 1.49.0 (2023-10-03) ### Features
chore
v1.50.0
5b22e967981b604be6070f5b373555756a5c62f7
2023-05-16 16:19:24
AkshayaFoiger
feat(connector): [Stripe] implement Bancontact Bank Redirect for stripe (#1169)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fa9f3f108a4..1e2bb95d9ca 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -590,18 +590,21 @@ pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] - card_number: CardNumber, + card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] - card_exp_month: Secret<String>, + card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] - card_exp_year: Secret<String>, + card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] - card_holder_name: Secret<String>, + card_holder_name: Option<Secret<String>>, + + //Required by Stripes + billing_details: Option<BankRedirectBilling>, }, Blik { // Blik Code @@ -698,7 +701,7 @@ pub struct BankRedirectBilling { pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "[email protected]")] - pub email: Email, + pub email: Option<Email>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 1b0757b86ac..0561dc1b234 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -248,7 +248,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, - customer_email: Some(billing_details.email.clone()), + customer_email: billing_details.email.clone(), shopper_result_url: item.request.router_return_url.clone(), })), diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 3f176ecf79d..ec1ba217fe3 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1116,14 +1116,35 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod card_exp_month, card_exp_year, card_holder_name, + .. } => Ok(AdyenPaymentMethod::BancontactCard(Box::new( BancontactCardData { payment_type: PaymentType::Scheme, brand: "bcmc".to_string(), - number: card_number.clone(), - expiry_month: card_exp_month.clone(), - expiry_year: card_exp_year.clone(), - holder_name: card_holder_name.clone(), + number: card_number + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_number", + })? + .clone(), + expiry_month: card_exp_month + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_exp_month", + })? + .clone(), + expiry_year: card_exp_year + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_exp_year", + })? + .clone(), + holder_name: card_holder_name + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_holder_name", + })? + .clone(), }, ))), api_models::payments::BankRedirectData::Blik { blik_code } => { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index b105a217307..457d42925ec 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -238,10 +238,16 @@ fn get_bank_name( }, )?)?, })), - (StripePaymentMethodType::Sofort | StripePaymentMethodType::Giropay, _) => Ok(None), + ( + StripePaymentMethodType::Sofort + | StripePaymentMethodType::Giropay + | StripePaymentMethodType::Bancontact, + _, + ) => Ok(None), _ => Err(errors::ConnectorError::MismatchedPaymentData), } } + #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBankRedirectData { #[serde(rename = "payment_method_types[]")] @@ -392,6 +398,7 @@ pub enum StripePaymentMethodType { Becs, #[serde(rename = "bacs_debit")] Bacs, + Bancontact, #[serde(rename = "wechat_pay")] Wechatpay, Alipay, @@ -627,6 +634,10 @@ fn infer_stripe_bank_redirect_issuer( Some(storage_models::enums::PaymentMethodType::Sofort) => { Ok(StripePaymentMethodType::Sofort) } + + Some(storage_models::enums::PaymentMethodType::BancontactCard) => { + Ok(StripePaymentMethodType::Bancontact) + } Some(storage_models::enums::PaymentMethodType::Przelewy24) => { Ok(StripePaymentMethodType::Przelewy24) } @@ -732,7 +743,19 @@ impl TryFrom<&payments::BankRedirectData> for StripeBillingAddress { payments::BankRedirectData::Przelewy24 { billing_details, .. } => Ok(Self { - email: Some(billing_details.email.clone()), + email: billing_details.email.clone(), + ..Self::default() + }), + payments::BankRedirectData::BancontactCard { + billing_details, .. + } => Ok(Self { + name: billing_details + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.billing_name", + })? + .billing_name + .clone(), ..Self::default() }), _ => Ok(Self::default()), @@ -876,6 +899,7 @@ fn create_stripe_payment_method( let pm_type = infer_stripe_bank_redirect_issuer(pm_type)?; let bank_specific_data = get_bank_specific_data(bank_redirect_data); let bank_name = get_bank_name(&pm_type, bank_redirect_data)?; + Ok(( StripePaymentMethodData::BankRedirect(StripeBankRedirectData { payment_method_types: pm_type, @@ -1346,6 +1370,7 @@ impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::Mandat | StripePaymentMethodOptions::WechatPay {} | StripePaymentMethodOptions::Alipay {} | StripePaymentMethodOptions::Sepa {} + | StripePaymentMethodOptions::Bancontact {} | StripePaymentMethodOptions::Przelewy24 {} => None, }), payment_method_id: Some(payment_method_id), @@ -1758,6 +1783,7 @@ pub enum StripePaymentMethodOptions { Becs {}, #[serde(rename = "bacs_debit")] Bacs {}, + Bancontact {}, WechatPay {}, Alipay {}, #[serde(rename = "p24")]
feat
[Stripe] implement Bancontact Bank Redirect for stripe (#1169)
86f4060d332b3515a92010287be32fe69508d451
2024-06-26 16:48:17
Sahkal Poddar
refactor(connector): added amount conversion framework for cashtocode (#4857)
false
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs index 279ad23259f..ec8c60002f0 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/router/src/connector/cashtocode.rs @@ -1,8 +1,10 @@ pub mod transformers; -use std::fmt::Debug; use base64::Engine; -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, +}; use diesel_models::enums; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -27,8 +29,18 @@ use crate::{ utils::{ByteSliceExt, BytesExt}, }; -#[derive(Debug, Clone)] -pub struct Cashtocode; +#[derive(Clone)] +pub struct Cashtocode { + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Cashtocode { + pub fn new() -> &'static Self { + &Self { + amount_converter: &FloatMajorUnitForConnector, + } + } +} impl api::Payment for Cashtocode {} impl api::PaymentSession for Cashtocode {} @@ -227,7 +239,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = cashtocode::CashtocodePaymentsRequest::try_from(req)?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_req = cashtocode::CashtocodePaymentsRequest::try_from((req, amount))?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs index 93922449b86..e6f4b9e57cf 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/router/src/connector/cashtocode/transformers.rs @@ -1,7 +1,9 @@ use std::collections::HashMap; pub use common_utils::request::Method; -use common_utils::{errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email}; +use common_utils::{ + errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit, +}; use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -16,7 +18,7 @@ use crate::{ #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsRequest { - amount: f64, + amount: FloatMajorUnit, transaction_id: String, user_id: Secret<id_type::CustomerId>, currency: enums::Currency, @@ -48,9 +50,11 @@ fn get_mid( } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for CashtocodePaymentsRequest { +impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit), + ) -> Result<Self, Self::Error> { let customer_id = item.get_customer_id()?; let url = item.request.get_router_return_url()?; let mid = get_mid( @@ -60,10 +64,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CashtocodePaymentsRequest )?; match item.payment_method { diesel_models::enums::PaymentMethod::Reward => Ok(Self { - amount: utils::to_currency_base_unit_asf64( - item.request.amount, - item.request.currency, - )?, + amount, transaction_id: item.attempt_id.clone(), currency: item.request.currency, user_id: Secret::new(customer_id.to_owned()), @@ -192,7 +193,7 @@ pub struct CashtocodePaymentsResponseData { #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsSyncResponse { pub transaction_id: String, - pub amount: f64, + pub amount: FloatMajorUnit, } fn get_redirect_form_data( @@ -330,7 +331,7 @@ pub struct CashtocodeErrorResponse { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodeIncomingWebhook { - pub amount: f64, + pub amount: FloatMajorUnit, pub currency: String, pub foreign_transaction_id: String, #[serde(rename = "type")] diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 1101d42d4c1..215003f8fb2 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -196,6 +196,7 @@ impl<F, T> status, response, amount_captured, + minor_amount_captured: amount_captured_in_minor_units, ..item.data }) } diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index c7039c25d49..97075aff79f 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -31,7 +31,6 @@ use crate::{ transformers::ForeignTryFrom, ErrorResponse, Response, }, - // transformers::{ForeignFrom, ForeignTryFrom}, utils::{handle_json_response_deserialization_failure, BytesExt}, }; @@ -50,7 +49,6 @@ impl Payme { } } } -// dummy commit impl api::Payment for Payme {} impl api::PaymentSession for Payme {} impl api::PaymentsCompleteAuthorize for Payme {} diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 5dcb8db05a5..03ea2b2d613 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -371,7 +371,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Braintree))) } enums::Connector::Cashtocode => { - Ok(ConnectorEnum::Old(Box::new(&connector::Cashtocode))) + Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new()))) } enums::Connector::Checkout => { Ok(ConnectorEnum::Old(Box::new(&connector::Checkout))) diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 0b802de3195..3e2708fb1f4 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -13,7 +13,7 @@ impl utils::Connector for CashtocodeTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Cashtocode; utils::construct_connector_data_old( - Box::new(&Cashtocode), + Box::new(Cashtocode::new()), types::Connector::Cashtocode, types::api::GetToken::Connector, None,
refactor
added amount conversion framework for cashtocode (#4857)
9f334c1ebcf0e8ee15ae2af608fb8f27fab2a6b2
2025-02-24 05:59:14
github-actions
chore(version): 2025.02.24.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index f85a7d2ff42..7351e838c66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,30 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2025.02.24.0 + +### Features + +- **connector:** + - Add Samsung pay mandate support for Cybersource ([#7298](https://github.com/juspay/hyperswitch/pull/7298)) ([`9bc8fd4`](https://github.com/juspay/hyperswitch/commit/9bc8fd4d8c4be1b54050398dfb3b574e924e4b5f)) + - Add support for passive churn recovery webhooks ([#7109](https://github.com/juspay/hyperswitch/pull/7109)) ([`0688972`](https://github.com/juspay/hyperswitch/commit/0688972814cf03edbff4bf125a59c338a7e49593)) +- **router:** Add `merchant_configuration_id` in netcetera metadata and make other merchant configurations optional ([#7347](https://github.com/juspay/hyperswitch/pull/7347)) ([`57ab869`](https://github.com/juspay/hyperswitch/commit/57ab8693e26a54cd5fe73b28459c9b03235e5d5b)) +- **samsung_pay:** Collect customer address details form Samsung Pay based on business profile config and connector required fields ([#7320](https://github.com/juspay/hyperswitch/pull/7320)) ([`c14519e`](https://github.com/juspay/hyperswitch/commit/c14519ebd958abc79879244f8180686b2be30d31)) + +### Bug Fixes + +- **connector:** [DATATRANS] Fix Force Sync Flow ([#7331](https://github.com/juspay/hyperswitch/pull/7331)) ([`0e96e24`](https://github.com/juspay/hyperswitch/commit/0e96e2470c6906fe77b35c14821e3ebcfa454e39)) +- **routing:** Fixed 5xx error logs in dynamic routing metrics ([#7335](https://github.com/juspay/hyperswitch/pull/7335)) ([`049fcdb`](https://github.com/juspay/hyperswitch/commit/049fcdb3fb19c6af45392a5ef3a0cbf642598af8)) +- **samsung_pay:** Add payment_method_type duplication check ([#7337](https://github.com/juspay/hyperswitch/pull/7337)) ([`11ff437`](https://github.com/juspay/hyperswitch/commit/11ff437456f9d97205ce07e4d4df63006f3ad0c6)) + +### Miscellaneous Tasks + +- **masking:** Add peek_mut to PeekInterface ([#7281](https://github.com/juspay/hyperswitch/pull/7281)) ([`890a265`](https://github.com/juspay/hyperswitch/commit/890a265e7b1b06aeea100994efbebe3ce898a125)) + +**Full Changelog:** [`2025.02.21.0...2025.02.24.0`](https://github.com/juspay/hyperswitch/compare/2025.02.21.0...2025.02.24.0) + +- - - + ## 2025.02.21.0 ### Features
chore
2025.02.24.0
b8b206057c5b464420a6d115a1116ef5cc695bf7
2024-11-06 22:44:03
awasthi21
fix(core): PMD Not Getting Populated for Saved Card Transactions (#6497)
false
diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs index 4e1270f419c..27096c2a63b 100644 --- a/crates/router/src/connector/paybox/transformers.rs +++ b/crates/router/src/connector/paybox/transformers.rs @@ -1109,7 +1109,16 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for |data| Some(data.clone()), ), customer_id: match item.router_data.request.is_mandate_payment() { - true => Some(Secret::new(item.router_data.payment_id.clone())), + true => { + let reference_id = item + .router_data + .connector_mandate_request_reference_id + .clone() + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_request_reference_id", + })?; + Some(Secret::new(reference_id)) + } false => None, }, }) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 1bd3ddce735..635b3c24cf2 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -576,41 +576,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_method_info, } = mandate_details; - let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info { - let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm - .payment_method_data - .clone() - .map(|x| x.into_inner().expose()) - .and_then(|v| { - v.parse_value("PaymentMethodsData") - .map_err(|err| { - router_env::logger::info!( - "PaymentMethodsData deserialization failed: {:?}", - err - ) - }) - .ok() - }) - .and_then(|pmd| match pmd { - PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), - _ => None, - }); - card_detail_from_locker.map(|card_details| { - let additional_data = card_details.into(); - api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data)) - }) - } else { - None - }; - payment_attempt.payment_method_data = additional_pm_data_from_locker - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to encode additional pm data")?; - - payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); - payment_attempt.payment_method_type = payment_method_type .or(payment_attempt.payment_method_type) .or(payment_method_info @@ -650,6 +615,41 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } else { (None, payment_method_info) }; + let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info { + let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm + .payment_method_data + .clone() + .map(|x| x.into_inner().expose()) + .and_then(|v| { + v.parse_value("PaymentMethodsData") + .map_err(|err| { + router_env::logger::info!( + "PaymentMethodsData deserialization failed: {:?}", + err + ) + }) + .ok() + }) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + card_detail_from_locker.map(|card_details| { + let additional_data = card_details.into(); + api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data)) + }) + } else { + None + }; + payment_attempt.payment_method_data = additional_pm_data_from_locker + .as_ref() + .map(Encode::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data")?; + + payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); + // The operation merges mandate data from both request and payment_attempt let setup_mandate = mandate_data.map(|mut sm| { sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
fix
PMD Not Getting Populated for Saved Card Transactions (#6497)
cdca284b2a7a77cb22074fa8b3b380a088c10f00
2023-11-03 20:43:18
github-actions
chore(version): v1.71.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 41caed32f59..7c492d22bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.71.0 (2023-11-03) + +### Features + +- **merchant_connector_account:** Add cache for querying by `merchant_connector_id` ([#2738](https://github.com/juspay/hyperswitch/pull/2738)) ([`1ba6282`](https://github.com/juspay/hyperswitch/commit/1ba6282699b7dff5e6e95c9a14e51c0f8bf749cd)) +- **router:** Add Smart Routing to route payments efficiently ([#2665](https://github.com/juspay/hyperswitch/pull/2665)) ([`9b618d2`](https://github.com/juspay/hyperswitch/commit/9b618d24476967d364835d04010d9076a80aeb9c)) + +### Bug Fixes + +- **connector:** + - [Cryptopay]Remove default case handling for Cryptopay ([#2699](https://github.com/juspay/hyperswitch/pull/2699)) ([`255a4f8`](https://github.com/juspay/hyperswitch/commit/255a4f89a8e0124310d42bb63ad459bd8cde2cba)) + - [Bluesnap] fix psync status to failure when it is '403' ([#2772](https://github.com/juspay/hyperswitch/pull/2772)) ([`9314d14`](https://github.com/juspay/hyperswitch/commit/9314d1446326fd8a69f1f69657a976bbe7c27901)) +- Response spelling ([#2779](https://github.com/juspay/hyperswitch/pull/2779)) ([`5859372`](https://github.com/juspay/hyperswitch/commit/585937204d9071baa37d402f73159f8f650d0a07)) + +### Testing + +- **postman:** Update postman collection files ([`21e8a10`](https://github.com/juspay/hyperswitch/commit/21e8a105f9b47ded232b457a0420ad71ec2414ed)) + +**Full Changelog:** [`v1.70.1...v1.71.0`](https://github.com/juspay/hyperswitch/compare/v1.70.1...v1.71.0) + +- - - + + ## 1.70.1 (2023-11-03) ### Revert
chore
v1.71.0
07926050887cdd5d9e3a558ede4212074d17e257
2023-09-09 23:08:45
Hudson C. Dalprá
feat(db): implement `BusinessProfileInterface` for `MockDb` (#2101)
false
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 74c75a2bf56..23fe0aed33f 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -70,3 +70,51 @@ pub struct BusinessProfileUpdateInternal { pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: Option<bool>, } + +impl From<BusinessProfileNew> for BusinessProfile { + fn from(new: BusinessProfileNew) -> Self { + Self { + profile_id: new.profile_id, + merchant_id: new.merchant_id, + profile_name: new.profile_name, + created_at: new.created_at, + modified_at: new.modified_at, + return_url: new.return_url, + enable_payment_response_hash: new.enable_payment_response_hash, + payment_response_hash_key: new.payment_response_hash_key, + redirect_to_merchant_with_http_post: new.redirect_to_merchant_with_http_post, + webhook_details: new.webhook_details, + metadata: new.metadata, + routing_algorithm: new.routing_algorithm, + intent_fulfillment_time: new.intent_fulfillment_time, + frm_routing_algorithm: new.frm_routing_algorithm, + payout_routing_algorithm: new.payout_routing_algorithm, + is_recon_enabled: new.is_recon_enabled, + } + } +} + +impl BusinessProfileUpdateInternal { + pub fn apply_changeset(self, source: BusinessProfile) -> BusinessProfile { + BusinessProfile { + profile_name: self.profile_name.unwrap_or(source.profile_name), + modified_at: self.modified_at.unwrap_or(source.modified_at), + return_url: self.return_url, + enable_payment_response_hash: self + .enable_payment_response_hash + .unwrap_or(source.enable_payment_response_hash), + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self + .redirect_to_merchant_with_http_post + .unwrap_or(source.redirect_to_merchant_with_http_post), + webhook_details: self.webhook_details, + metadata: self.metadata, + routing_algorithm: self.routing_algorithm, + intent_fulfillment_time: self.intent_fulfillment_time, + frm_routing_algorithm: self.frm_routing_algorithm, + payout_routing_algorithm: self.payout_routing_algorithm, + is_recon_enabled: self.is_recon_enabled.unwrap_or(source.is_recon_enabled), + ..source + } + } +} diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs index 72b1d16edcc..dff3bac792e 100644 --- a/crates/router/src/db/business_profile.rs +++ b/crates/router/src/db/business_profile.rs @@ -114,38 +114,90 @@ impl BusinessProfileInterface for Store { impl BusinessProfileInterface for MockDb { async fn insert_business_profile( &self, - _business_profile: business_profile::BusinessProfileNew, + business_profile: business_profile::BusinessProfileNew, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let business_profile_insert = business_profile::BusinessProfile::from(business_profile); + self.business_profiles + .lock() + .await + .push(business_profile_insert.clone()); + Ok(business_profile_insert) } async fn find_business_profile_by_profile_id( &self, - _profile_id: &str, + profile_id: &str, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + self.business_profiles + .lock() + .await + .iter() + .find(|business_profile| business_profile.profile_id == profile_id) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {}", + profile_id + )) + .into(), + ) + .cloned() } async fn update_business_profile_by_profile_id( &self, - _current_state: business_profile::BusinessProfile, - _business_profile_update: business_profile::BusinessProfileUpdateInternal, + current_state: business_profile::BusinessProfile, + business_profile_update: business_profile::BusinessProfileUpdateInternal, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + self.business_profiles + .lock() + .await + .iter_mut() + .find(|bp| bp.profile_id == current_state.profile_id) + .map(|bp| { + let business_profile_updated = + business_profile_update.apply_changeset(current_state.clone()); + *bp = business_profile_updated.clone(); + business_profile_updated + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {}", + current_state.profile_id + )) + .into(), + ) } async fn delete_business_profile_by_profile_id_merchant_id( &self, - _profile_id: &str, - _merchant_id: &str, + profile_id: &str, + merchant_id: &str, ) -> CustomResult<bool, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let mut business_profiles = self.business_profiles.lock().await; + let index = business_profiles + .iter() + .position(|bp| bp.profile_id == profile_id && bp.merchant_id == merchant_id) + .ok_or::<errors::StorageError>(errors::StorageError::ValueNotFound(format!( + "No business profile found for profile_id = {} and merchant_id = {}", + profile_id, merchant_id + )))?; + business_profiles.remove(index); + Ok(true) } async fn list_business_profile_by_merchant_id( &self, - _merchant_id: &str, + merchant_id: &str, ) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let business_profile_by_merchant_id = self + .business_profiles + .lock() + .await + .iter() + .filter(|business_profile| business_profile.merchant_id == merchant_id) + .cloned() + .collect(); + + Ok(business_profile_by_merchant_id) } } diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 39ea480a789..5ff4d000b85 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -237,6 +237,7 @@ pub struct MockDb { pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<crate::store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<crate::store::merchant_key_store::MerchantKeyStore>>>, + pub business_profiles: Arc<Mutex<Vec<crate::store::business_profile::BusinessProfile>>>, } impl MockDb { @@ -263,6 +264,7 @@ impl MockDb { mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), + business_profiles: Default::default(), } } }
feat
implement `BusinessProfileInterface` for `MockDb` (#2101)
164d1c66fbcb84104db07412496114db2f8c5c0c
2023-11-08 15:59:13
Sampras Lopes
feat(events): add request details to api events (#2769)
false
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 35eaf1edae7..5a66ba3e0bf 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -1,3 +1,4 @@ +use actix_web::HttpRequest; use router_env::{tracing_actix_web::RequestId, types::FlowMetric}; use serde::Serialize; use time::OffsetDateTime; @@ -15,10 +16,14 @@ pub struct ApiEvent { #[serde(flatten)] auth_type: AuthenticationType, request: serde_json::Value, + user_agent: Option<String>, + ip_addr: Option<String>, + url_path: String, response: Option<serde_json::Value>, } impl ApiEvent { + #[allow(clippy::too_many_arguments)] pub fn new( api_flow: &impl FlowMetric, request_id: &RequestId, @@ -27,6 +32,7 @@ impl ApiEvent { request: serde_json::Value, response: Option<serde_json::Value>, auth_type: AuthenticationType, + http_req: &HttpRequest, ) -> Self { Self { api_flow: api_flow.to_string(), @@ -37,6 +43,15 @@ impl ApiEvent { request, response, auth_type, + ip_addr: http_req + .connection_info() + .realip_remote_addr() + .map(ToOwned::to_owned), + user_agent: http_req + .headers() + .get("user-agent") + .and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)), + url_path: http_req.path().to_string(), } } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index c942f09f96a..36264490697 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -852,6 +852,7 @@ where serialized_request, serialized_response, auth_type, + request, ); match api_event.clone().try_into() { Ok(event) => {
feat
add request details to api events (#2769)
88cf904f5b01d890c25ff7fe22d25c634ec5a785
2024-06-11 20:23:05
Chethan Rao
refactor: wrap the encryption and file storage interface client in appstate with `Arc` as opposed to `Box` (#4949)
false
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 311cee0cede..e64b5dbd4ad 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -31,7 +31,7 @@ pub struct CmdLineConf { #[derive(Clone)] pub struct AppState { pub conf: Arc<Settings<RawSecret>>, - pub encryption_client: Box<dyn EncryptionManagementInterface>, + pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl AppState { diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs index fb419b6ec64..e551cfee2af 100644 --- a/crates/external_services/src/file_storage.rs +++ b/crates/external_services/src/file_storage.rs @@ -2,7 +2,10 @@ //! Module for managing file storage operations with support for multiple storage schemes. //! -use std::fmt::{Display, Formatter}; +use std::{ + fmt::{Display, Formatter}, + sync::Arc, +}; use common_utils::errors::CustomResult; @@ -39,11 +42,11 @@ impl FileStorageConfig { } /// Retrieves the appropriate file storage client based on the file storage configuration. - pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> { match self { #[cfg(feature = "aws_s3")] - Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), - Self::FileSystem => Box::new(file_system::FileSystem), + Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Arc::new(file_system::FileSystem), } } } diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs index 4612190926c..678239c60b1 100644 --- a/crates/external_services/src/managers/encryption_management.rs +++ b/crates/external_services/src/managers/encryption_management.rs @@ -2,6 +2,8 @@ //! Encryption management util module //! +use std::sync::Arc; + use common_utils::errors::CustomResult; use hyperswitch_interfaces::encryption_interface::{ EncryptionError, EncryptionManagementInterface, @@ -42,12 +44,12 @@ impl EncryptionManagementConfig { /// Retrieves the appropriate encryption client based on the configuration. pub async fn get_encryption_management_client( &self, - ) -> CustomResult<Box<dyn EncryptionManagementInterface>, EncryptionError> { + ) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> { Ok(match self { #[cfg(feature = "aws_kms")] - Self::AwsKms { aws_kms } => Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await), + Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await), - Self::NoEncryption => Box::new(NoEncryption), + Self::NoEncryption => Arc::new(NoEncryption), }) } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 83d8c714e92..8d88d9c4b26 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -82,7 +82,7 @@ pub struct SessionState { pub email_client: Arc<dyn EmailService>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, - pub file_storage_client: Box<dyn FileStorageInterface>, + pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: String, @@ -144,8 +144,8 @@ pub struct AppState { #[cfg(feature = "olap")] pub opensearch_client: Arc<OpenSearchClient>, pub request_id: Option<RequestId>, - pub file_storage_client: Box<dyn FileStorageInterface>, - pub encryption_client: Box<dyn EncryptionManagementInterface>, + pub file_storage_client: Arc<dyn FileStorageInterface>, + pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<String> {
refactor
wrap the encryption and file storage interface client in appstate with `Arc` as opposed to `Box` (#4949)
4f5a383bab567a1b46b2d6990c0c23ed60f1201b
2023-10-10 18:56:20
DEEPANSHU BANSAL
chore: [GOCARDLESS] env changes for becs and sepa mandates (#2535)
false
diff --git a/config/config.example.toml b/config/config.example.toml index b69519b6ac4..e827beff8cc 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -350,6 +350,8 @@ card.credit = {connector_list = "stripe,adyen"} # Mandate supported payment 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 # Required fields info used while listing the payment_method_data [required_fields.pay_later] # payment_method = "pay_later" diff --git a/config/development.toml b/config/development.toml index 75a5a89ca9d..91451a69c16 100644 --- a/config/development.toml +++ b/config/development.toml @@ -419,6 +419,8 @@ wallet.paypal = { connector_list = "adyen" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } card.debit = { connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } bank_debit.ach = { connector_list = "gocardless"} +bank_debit.becs = { connector_list = "gocardless"} +bank_debit.sepa = { connector_list = "gocardless"} [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 b1483327ee0..b8525e9b5f5 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -297,6 +297,8 @@ wallet.paypal = {connector_list = "adyen"} card.credit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} card.debit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} bank_debit.ach = { connector_list = "gocardless"} +bank_debit.becs = { connector_list = "gocardless"} +bank_debit.sepa = { connector_list = "gocardless"} [connector_customer] connector_list = "gocardless,stax,stripe" diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 8187c5ccc49..c5322ccf7fc 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -582,7 +582,7 @@ impl<F> mandate_reference, network_txn_id: None, }), - status: enums::AttemptStatus::Pending, + status: enums::AttemptStatus::Charged, ..item.data }) } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index db6ed0850c8..38037304968 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -228,3 +228,5 @@ wallet.paypal = {connector_list = "adyen"} card.credit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} card.debit = {connector_list = "stripe,adyen,authorizedotnet,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} bank_debit.ach = { connector_list = "gocardless"} +bank_debit.becs = { connector_list = "gocardless"} +bank_debit.sepa = { connector_list = "gocardless"}
chore
[GOCARDLESS] env changes for becs and sepa mandates (#2535)
6a487b195bf12f30d1c1f5d7f1ce679cff166317
2023-02-25 18:53:53
Gnanasundari24
chore(connectors): log connector request and response at debug level (#624)
false
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 648464c4c8f..070e2b8f06c 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -8,8 +8,7 @@ use transformers as aci; use crate::{ configs::settings, core::errors::{self, CustomResult}, - headers, - services::{self, logger}, + headers, services, types::{ self, api::{self, ConnectorCommon}, @@ -242,7 +241,6 @@ impl // encode only for for urlencoded things. let aci_req = utils::Encode::<aci::AciPaymentsRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - logger::debug!(aci_payment_logs=?aci_req); Ok(Some(aci_req)) } @@ -484,8 +482,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(response=?res); - let response: aci::AciRefundResponse = res .response .parse_struct("AciRefundResponse") diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index e3f24358887..2c56b605111 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -12,7 +12,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, services, + headers, services, types::{ self, api::{self, ConnectorCommon}, @@ -123,7 +123,6 @@ impl .build(), ); - logger::debug!(braintree_session_request=?request); Ok(request) } @@ -131,7 +130,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(braintree_payments_error_response=?res); let response: braintree::ErrorResponse = res .response .parse_struct("Error Response") @@ -153,7 +151,6 @@ impl utils::Encode::<braintree::BraintreeSessionRequest>::convert_and_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - logger::debug!(?braintree_session_request); Ok(Some(braintree_session_request)) } @@ -162,7 +159,6 @@ impl data: &types::PaymentsSessionRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { - logger::debug!(payment_session_response_braintree=?res); let response: braintree::BraintreeSessionTokenResponse = res .response .parse_struct("braintree SessionTokenResponse") @@ -291,7 +287,6 @@ impl data: &types::PaymentsSyncRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response_braintree=?res); let response: braintree::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsResponse") @@ -380,7 +375,6 @@ impl data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(braintreepayments_create_response=?res); let response: braintree::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsResponse") @@ -398,8 +392,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(braintreepayments_create_response=?res); - let response: braintree::ErrorResponse = res .response .parse_struct("Braintree ErrorResponse") @@ -502,7 +494,6 @@ impl data: &types::PaymentsCancelRouterData, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response=?res); let response: braintree::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsVoidResponse") @@ -593,7 +584,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(target: "router::connector::braintree", response=?res); let response: braintree::RefundResponse = res .response .parse_struct("Braintree RefundResponse") @@ -669,7 +659,6 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, errors::ConnectorError, > { - logger::debug!(target: "router::connector::braintree", response=?res); let response: braintree::RefundResponse = res .response .parse_struct("Braintree RefundResponse") diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index ea4c4697c95..f262b7d9ec0 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -15,7 +15,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, services, + headers, services, types::{ self, api::{self, ConnectorCommon}, @@ -262,12 +262,10 @@ impl types::PaymentsSyncData: Clone, types::PaymentsResponseData: Clone, { - logger::debug!(raw_response=?res); let response: checkout::PaymentsResponse = res .response .parse_struct("PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(payment_sync_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -280,7 +278,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(raw_response=?res); let response: checkout::ErrorResponse = res .response .parse_struct("ErrorResponse") @@ -370,7 +367,6 @@ impl data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(payments_create_response=?res); let response: checkout::PaymentsResponse = res .response .parse_struct("PaymentIntentResponse") @@ -387,8 +383,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(checkout_error_response=?res); - let response: checkout::ErrorResponse = if res.response.is_empty() { checkout::ErrorResponse { request_id: None, @@ -485,8 +479,6 @@ impl data: &types::PaymentsCancelRouterData, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { - logger::debug!(payments_cancel_response=?res); - let mut response: checkout::PaymentVoidResponse = res .response .parse_struct("PaymentVoidResponse") @@ -595,7 +587,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(response=?res); let response: checkout::RefundResponse = res .response .parse_struct("checkout::RefundResponse") diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 998ccdc3639..69118abfd5c 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -14,7 +14,7 @@ use crate::{ connector::utils::RefundsRequestData, consts, core::errors::{self, CustomResult}, - headers, logger, + headers, services::{self, ConnectorIntegration}, types::{ self, @@ -265,7 +265,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Cybersource PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersourcepayments_create_response=?response); types::RouterData::try_from(( types::ResponseRouterData { response, @@ -348,7 +347,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("Cybersource PaymentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersourcepayments_create_response=?response); let is_auto_capture = data.request.capture_method == Some(storage_models::enums::CaptureMethod::Automatic); types::RouterData::try_from(( @@ -436,7 +434,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Cybersource PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersourcepayments_create_response=?response); let is_auto_capture = data.request.capture_method == Some(storage_models::enums::CaptureMethod::Automatic); types::RouterData::try_from(( @@ -517,7 +514,6 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Cybersource PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersourcepayments_create_response=?response); types::RouterData::try_from(( types::ResponseRouterData { response, @@ -607,7 +603,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("Cybersource PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersource_refund_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -675,7 +670,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("Cybersource RefundsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(cybersourcepayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 61844e64e3e..fbbdb13942f 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -19,7 +19,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + headers, services::{self, ConnectorIntegration}, types::{ self, @@ -160,7 +160,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t data: &types::RefreshTokenRouterData, res: types::Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { - logger::debug!(globalpaypayments_raw_refresh_token_response=?res); let response: GlobalpayRefreshTokenResponse = res .response .parse_struct("Globalpay PaymentsResponse") @@ -265,7 +264,6 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(globalpaypayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -340,7 +338,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response=?res); let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay PaymentsResponse") @@ -419,7 +416,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(globalpaypayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -508,7 +504,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(globalpaypayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -591,7 +586,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(target: "router::connector::globalpay", response=?res); let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay RefundResponse") @@ -666,7 +660,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: &types::RefundSyncRouterData, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - logger::debug!(target: "router::connector::globalpay", response=?res); let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay RefundResponse") diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 38e576cffd6..a6d0efc8577 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -9,7 +9,7 @@ use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, - services::{self, logger}, + services::{self}, types::{ self, api::{self, ConnectorCommon}, @@ -113,7 +113,6 @@ impl let klarna_req = utils::Encode::<klarna::KlarnaSessionRequest>::encode_to_string_of_json(&connector_req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - logger::debug!(klarna_session_request_logs=?klarna_req); Ok(Some(klarna_req)) } @@ -139,7 +138,6 @@ impl data: &types::PaymentsSessionRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { - logger::debug!(klarna_session_response_logs=?res); let response: klarna::KlarnaSessionResponse = res .response .parse_struct("KlarnaSessionResponse") @@ -156,7 +154,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(klarna_session_error_logs=?res); let response: klarna::KlarnaErrorResponse = res .response .parse_struct("KlarnaErrorResponse") @@ -274,7 +271,6 @@ impl &connector_req, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - logger::debug!(klarna_payment_logs=?klarna_req); Ok(Some(klarna_req)) } @@ -302,7 +298,6 @@ impl data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(klarna_raw_response=?res); let response: klarna::KlarnaPaymentsResponse = res .response .parse_struct("KlarnaPaymentsResponse") @@ -319,7 +314,6 @@ impl &self, res: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - logger::debug!(klarna_error_response=?res); let response: klarna::KlarnaErrorResponse = res .response .parse_struct("KlarnaErrorResponse") diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index 3972f9c62b3..e29b55760e5 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -11,7 +11,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + headers, services::{self, ConnectorIntegration}, types::{ self, @@ -79,7 +79,6 @@ impl ConnectorCommon for Payu { &self, res: types::Response, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - logger::debug!(payu_error_response=?res); let response: payu::PayuErrorResponse = res .response .parse_struct("Payu ErrorResponse") @@ -153,7 +152,6 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("PaymentCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(payments_create_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -208,7 +206,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t let payu_req = utils::Encode::<payu::PayuAuthUpdateRequest>::convert_and_url_encode(req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - logger::debug!(payu_access_token_request=?payu_req); Ok(Some(payu_req)) } @@ -226,8 +223,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .build(), ); - logger::debug!(payu_access_token_request=?req); - Ok(req) } fn handle_response( @@ -235,7 +230,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t data: &types::RefreshTokenRouterData, res: types::Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { - logger::debug!(access_token_response=?res); let response: payu::PayuAuthUpdateResponse = res .response .parse_struct("payu PayuAuthUpdateResponse") @@ -254,7 +248,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t &self, res: types::Response, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - logger::debug!(access_token_error_response=?res); let response: payu::PayuAccessTokenErrorResponse = res .response .parse_struct("Payu AccessTokenErrorResponse") @@ -322,7 +315,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(target: "router::connector::payu", response=?res); let response: payu::PayuPaymentsSyncResponse = res .response .parse_struct("payu OrderResponse") @@ -509,7 +501,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("PayuPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(payupayments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -590,7 +581,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(target: "router::connector::payu", response=?res); let response: payu::RefundResponse = res .response .parse_struct("payu RefundResponse") @@ -658,7 +648,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: &types::RefundSyncRouterData, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - logger::debug!(target: "router::connector::payu", response=?res); let response: payu::RefundSyncResponse = res.response .parse_struct("payu RefundResponse") diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index cc515d3d8e9..ee4386e2100 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -14,7 +14,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + headers, services::{self, ConnectorIntegration}, types::{ self, @@ -176,7 +176,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response=?res); let response: shift4::Shift4PaymentsResponse = res .response .parse_struct("shift4 PaymentsResponse") @@ -232,7 +231,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Shift4PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(shift4payments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -332,7 +330,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Shift4PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(shift4payments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -405,7 +402,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(target: "router::connector::shift4", response=?res); let response: shift4::RefundResponse = res .response .parse_struct("RefundResponse") @@ -473,7 +469,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse data: &types::RefundSyncRouterData, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - logger::debug!(target: "router::connector::shift4", response=?res); let response: shift4::RefundResponse = res.response .parse_struct("shift4 RefundResponse") diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 8e54d50fc49..a93246114cd 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -15,7 +15,7 @@ use crate::{ payments, }, db::StorageInterface, - headers, logger, services, + headers, services, types::{ self, api::{self, ConnectorCommon}, @@ -264,7 +264,6 @@ impl types::PaymentsAuthorizeData: Clone, types::PaymentsResponseData: Clone, { - logger::debug!(payment_sync_response=?res); let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") @@ -376,7 +375,6 @@ impl data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(stripe_payments_create_response=?res); let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") @@ -488,7 +486,6 @@ impl .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(payments_create_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -615,7 +612,6 @@ impl .response .parse_struct("SetupIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(setup_intent_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -714,8 +710,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref data: &types::RefundsRouterData<api::Execute>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(response=?res); - let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") @@ -809,8 +803,6 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, errors::ConnectorError, > { - logger::debug!(response=?res); - let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index ff41f8b1b88..852602ef152 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -15,7 +15,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + headers, services::{self, ConnectorIntegration}, types::{ self, @@ -300,7 +300,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme data: &types::PaymentsCaptureRouterData, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - logger::debug!(worldpaypayments_capture_response=?res); match res.status_code { 202 => { let response: WorldpayPaymentsResponse = res @@ -417,7 +416,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Worldpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(worldpaypayments_create_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -497,7 +495,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(target: "router::connector::worldpay", response=?res); match res.status_code { 202 => { let response: WorldpayPaymentsResponse = res diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index faf79a1a4a5..1a92a6f6cfd 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -164,7 +164,9 @@ where payments::CallConnectorAction::Trigger => { match connector_integration.build_request(req, &state.conf.connectors)? { Some(request) => { + logger::debug!(connector_request=?request); let response = call_connector_api(state, request).await; + logger::debug!(connector_response=?response); match response { Ok(body) => { let response = match body { @@ -176,7 +178,6 @@ where router_data } }; - logger::debug!(?response); Ok(response) } Err(error) => Err(error
chore
log connector request and response at debug level (#624)
f63a97024c755fd30a3403e2146812fe4edb8067
2024-05-07 12:59:28
Sarthak Soni
fix(payment_methods): fix deserialization errors for `sdk_eligible_payment_methods` (#4565)
false
diff --git a/config/config.example.toml b/config/config.example.toml index b5585a84b32..f0dad483c65 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -615,4 +615,4 @@ refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] \ No newline at end of file +sdk_eligible_payment_methods = "card" \ No newline at end of file diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index fe47b10b543..faf3bb7f466 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -321,4 +321,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of co keys = "user-agent" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] \ No newline at end of file +sdk_eligible_payment_methods = "card" \ No newline at end of file diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3135b3d5682..f564b976bc0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -332,4 +332,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of connec keys = "user-agent" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] \ No newline at end of file +sdk_eligible_payment_methods = "card" \ No newline at end of file diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 921301ebd6f..35c8a2ba3d6 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -336,4 +336,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of con keys = "user-agent" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] \ No newline at end of file +sdk_eligible_payment_methods = "card" \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index db7f1ed93f4..3f05872bc6a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -617,4 +617,4 @@ refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] +sdk_eligible_payment_methods = "card" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 702d134f2d5..9fd22f46707 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -476,4 +476,4 @@ refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" [saved_payment_methods] -sdk_eligible_payment_methods = ["card"] \ No newline at end of file +sdk_eligible_payment_methods = "card" \ No newline at end of file diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 12ce9c39d6f..adc09fb55af 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -167,7 +167,9 @@ pub struct PaymentMethodAuth { } #[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct EligiblePaymentMethods { + #[serde(deserialize_with = "deserialize_hashset")] pub sdk_eligible_payment_methods: HashSet<String>, }
fix
fix deserialization errors for `sdk_eligible_payment_methods` (#4565)
82a75da314cfda837b6582532200629e7aad7c11
2024-06-28 05:44:45
github-actions
chore(version): 2024.06.28.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index da79cb4c207..1d43bb1fa3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.06.28.0 + +### Features + +- **router:** Skip apple pay session call if the browser is not Safari ([#5136](https://github.com/juspay/hyperswitch/pull/5136)) ([`d4dba55`](https://github.com/juspay/hyperswitch/commit/d4dba55fedc37ba9d1d54d28456ca17851ab9881)) + +### Bug Fixes + +- **opensearch:** Show search results only if user has access permission to the index ([#5097](https://github.com/juspay/hyperswitch/pull/5097)) ([`9c49ded`](https://github.com/juspay/hyperswitch/commit/9c49ded104b81f1aefcc288e3ded64ebbd4d466f)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`aa1e8f2`](https://github.com/juspay/hyperswitch/commit/aa1e8f243f7e9e9e3b6e3f809fc404077af3057b)) +- Use generic phone numbers instead ([#5142](https://github.com/juspay/hyperswitch/pull/5142)) ([`57055ec`](https://github.com/juspay/hyperswitch/commit/57055ecab2300c2284d0e674a22247fa65776ed8)) + +**Full Changelog:** [`2024.06.27.0...2024.06.28.0`](https://github.com/juspay/hyperswitch/compare/2024.06.27.0...2024.06.28.0) + +- - - + ## 2024.06.27.0 ### Features
chore
2024.06.28.0
a2f179350a7e5819db1b6088b75ff3a7b1ad9bad
2024-03-11 15:47:54
github-actions
chore(version): 2024.03.11.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b135c61a50..4356b94bbf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,32 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.03.11.1 + +### Features + +- **router:** Add routing support for token-based mit payments ([#4012](https://github.com/juspay/hyperswitch/pull/4012)) ([`43ebfbc`](https://github.com/juspay/hyperswitch/commit/43ebfbc47f03eaaaf274847290861dcb00db26a5)) +- **users:** Implemented Set-Cookie ([#3865](https://github.com/juspay/hyperswitch/pull/3865)) ([`44eef46`](https://github.com/juspay/hyperswitch/commit/44eef46e5d7f0a198be80602ceae1c843449319c)) + +### Refactors + +- **connector:** + - [Multisafepay] Mask PII data ([#3869](https://github.com/juspay/hyperswitch/pull/3869)) ([`c2b1561`](https://github.com/juspay/hyperswitch/commit/c2b15615e3c61e6f497180be8fa66d008ed150bb)) + - [Globalpay] Mask PII data ([#3840](https://github.com/juspay/hyperswitch/pull/3840)) ([`13f6d6c`](https://github.com/juspay/hyperswitch/commit/13f6d6c10ce421329a7eb8b494fbb3bd31aed91f)) + - [Iatapay] Mask PII data ([#3850](https://github.com/juspay/hyperswitch/pull/3850)) ([`bd7accb`](https://github.com/juspay/hyperswitch/commit/bd7accb2c250b5f330b6bbb87f6f6edf4a479a61)) + - [Payme][Payeezy] Mask PII data ([#3926](https://github.com/juspay/hyperswitch/pull/3926)) ([`ffcb2bc`](https://github.com/juspay/hyperswitch/commit/ffcb2bcf2b7a26d8fc7fc45f9878d41ba74d2fe0)) + - [Nexinets] Mask PII data ([#3874](https://github.com/juspay/hyperswitch/pull/3874)) ([`9ea5310`](https://github.com/juspay/hyperswitch/commit/9ea531068d87b76e8f41ee7d9e9d26fd755bced4)) + - [Noon] Mask PII data ([#3879](https://github.com/juspay/hyperswitch/pull/3879)) ([`96efc2a`](https://github.com/juspay/hyperswitch/commit/96efc2abf94e3e9174f625bee2270236bad50278)) + - [stripe] capture error_code and error_message for psync ([#3771](https://github.com/juspay/hyperswitch/pull/3771)) ([`614182a`](https://github.com/juspay/hyperswitch/commit/614182ae4cdc7a762e0ce90d1336b1ff16fc9fa3)) + - [Trustpay][Volt] Mask PII data ([#3932](https://github.com/juspay/hyperswitch/pull/3932)) ([`a179b9c`](https://github.com/juspay/hyperswitch/commit/a179b9c90c2b9a419f1ce394d06158f80c29ee45)) + - [Nuvie] Mask PII data ([#3924](https://github.com/juspay/hyperswitch/pull/3924)) ([`6b2f71c`](https://github.com/juspay/hyperswitch/commit/6b2f71c850ff2ea36365375a81a7026fd8c87ebc)) + - [adyen] add more fields in the payments request ([#4010](https://github.com/juspay/hyperswitch/pull/4010)) ([`5584f11`](https://github.com/juspay/hyperswitch/commit/5584f1131ae4180020be23d4c735b8356482c22d)) +- **core:** Updated payments response with payment_method_id & payment_method_status ([#3883](https://github.com/juspay/hyperswitch/pull/3883)) ([`7391416`](https://github.com/juspay/hyperswitch/commit/7391416e2473eab0474bd01bb155a9ecc96da263)) + +**Full Changelog:** [`2024.03.11.0...2024.03.11.1`](https://github.com/juspay/hyperswitch/compare/2024.03.11.0...2024.03.11.1) + +- - - + ## 2024.03.11.0 ### Features
chore
2024.03.11.1
4364630d6ffbce43bef0947a0150ce255a43751a
2024-08-05 19:50:39
Sarthak Soni
fix(connector): Fixed status mapping for Plaid (#5525)
false
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs index 545ea271c43..cf9c91afd0c 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/router/src/connector/plaid/transformers.rs @@ -233,16 +233,16 @@ impl From<PlaidPaymentStatus> for enums::AttemptStatus { fn from(item: PlaidPaymentStatus) -> Self { match item { PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing, - PlaidPaymentStatus::PaymentStatusBlocked => Self::AuthorizationFailed, + PlaidPaymentStatus::PaymentStatusBlocked + | PlaidPaymentStatus::PaymentStatusInsufficientFunds + | PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed, PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided, PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized, - PlaidPaymentStatus::PaymentStatusExecuted => Self::Authorized, + PlaidPaymentStatus::PaymentStatusExecuted + | PlaidPaymentStatus::PaymentStatusSettled + | PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged, PlaidPaymentStatus::PaymentStatusFailed => Self::Failure, - PlaidPaymentStatus::PaymentStatusInitiated => Self::AuthenticationPending, PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending, - PlaidPaymentStatus::PaymentStatusInsufficientFunds => Self::AuthorizationFailed, - PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed, - PlaidPaymentStatus::PaymentStatusSettled => Self::Charged, } } }
fix
Fixed status mapping for Plaid (#5525)
9c331e411ba524ef41352c1c7c69635492fcec23
2023-05-08 19:04:43
SamraatBansal
feat(connector): [Bluesnap] add cards 3DS support (#1057)
false
diff --git a/config/development.toml b/config/development.toml index 4ecd69879cf..ad7ab4b4160 100644 --- a/config/development.toml +++ b/config/development.toml @@ -180,33 +180,33 @@ ideal = { country = "NL", currency = "EUR" } [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"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.klarna] klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,EUR,EUR,CAD,CZK,DKK,EUR,EUR,EUR,EUR,EUR,EUR,EUR,NZD,NOK,PLN,EUR,EUR,SEK,CHF,GBP,USD" } -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.zen] -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.aci] -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.mollie] -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.multisafepay] -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.trustpay] -credit = { not_available_flows = {capture_method="manual"} } -debit = { not_available_flows = {capture_method="manual"} } +credit = { not_available_flows = { capture_method = "manual" } } +debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.authorizedotnet] google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } @@ -221,15 +221,15 @@ bucket_name = "" region = "" [pm_filters.forte] -credit = {currency = "USD"} -debit = {currency = "USD"} +credit = { currency = "USD" } +debit = { currency = "USD" } [tokenization] stripe = { long_lived_token = false, payment_method = "wallet" } checkout = { long_lived_token = false, payment_method = "wallet" } [connector_customer] -connector_list = "stripe" +connector_list = "bluesnap, stripe" [dummy_connector] payment_ttl = 172800 diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a8c69d04e52..2a124398465 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -511,7 +511,7 @@ pub enum BankDebitData { }, } -#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { Card(Card), diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 3ed5f8f67a2..05246d3bdc6 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -71,9 +71,15 @@ where ), } } - Ok(api::ApplicationResponse::Form(form_data)) => api::build_redirection_form(&form_data) - .respond_to(request) - .map_into_boxed_body(), + Ok(api::ApplicationResponse::Form(redirection_data)) => api::build_redirection_form( + &redirection_data.redirect_form, + redirection_data.payment_method_data, + redirection_data.amount, + redirection_data.currency, + ) + .respond_to(request) + .map_into_boxed_body(), + Err(error) => { logger::error!(api_response_error=?error); api::log_and_return_error_response(error) diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index bf732635c15..3e443286773 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -596,6 +596,7 @@ fn get_error_response( types::Response { response, status_code, + .. }: types::Response, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: authorizedotnet::AuthorizedotnetPaymentsResponse = response diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 8d87979300c..abe5fe734e8 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -3,21 +3,28 @@ mod transformers; use std::fmt::Debug; use base64::Engine; -use common_utils::crypto; +use common_utils::{ + crypto, + ext_traits::{StringExt, ValueExt}, +}; use error_stack::{IntoReport, ResultExt}; use transformers as bluesnap; -use super::utils::RefundsRequestData; +use super::utils::{self as connector_utils, RefundsRequestData, RouterData}; use crate::{ configs::settings, consts, - core::errors::{self, CustomResult}, + core::{ + errors::{self, CustomResult}, + payments, + }, db::StorageInterface, headers, logger, services::{self, ConnectorIntegration}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, + storage::enums, ErrorResponse, Response, }, utils::{self, BytesExt}, @@ -128,6 +135,99 @@ impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::Payments { } +impl api::ConnectorCustomer for Bluesnap {} + +impl + ConnectorIntegration< + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > for Bluesnap +{ + fn get_headers( + &self, + req: &types::ConnectorCustomerRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::ConnectorCustomerRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}services/2/vaulted-shoppers", + self.base_url(connectors), + )) + } + + fn get_request_body( + &self, + req: &types::ConnectorCustomerRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_request = bluesnap::BluesnapCustomerRequest::try_from(req)?; + let bluesnap_req = + utils::Encode::<bluesnap::BluesnapCustomerRequest>::encode_to_string_of_json( + &connector_request, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(bluesnap_req)) + } + + fn build_request( + &self, + req: &types::ConnectorCustomerRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::ConnectorCustomerType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::ConnectorCustomerType::get_headers( + self, req, connectors, + )?) + .body(types::ConnectorCustomerType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::ConnectorCustomerRouterData, + res: Response, + ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> + where + types::PaymentsResponseData: Clone, + { + let response: bluesnap::BluesnapCustomerResponse = res + .response + .parse_struct("BluesnapCustomerResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl api::PaymentVoid for Bluesnap {} impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> @@ -414,14 +514,22 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "services/2/transactions" - )) + match req.is_three_ds() { + true => Ok(format!( + "{}{}{}", + self.base_url(connectors), + "services/2/payment-fields-tokens?shopperId=", + req.get_connector_customer_id()? + )), + _ => Ok(format!( + "{}{}", + self.base_url(connectors), + "services/2/transactions" + )), + } } fn get_request_body( @@ -462,16 +570,126 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + match (data.is_three_ds(), res.headers) { + (true, Some(headers)) => { + let location = connector_utils::get_http_header("Location", &headers)?; + let payment_fields_token = location + .split('/') + .last() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)? + .to_string(); + Ok(types::RouterData { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::BlueSnap { + payment_fields_token, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + ..data.clone() + }) + } + _ => { + let response: bluesnap::BluesnapPaymentsResponse = res + .response + .parse_struct("BluesnapPaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentsCompleteAuthorize for Bluesnap {} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Bluesnap +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}services/2/transactions", + self.base_url(connectors), + )) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_req = bluesnap::BluesnapPaymentsRequest::try_from(req)?; + let bluesnap_req = + utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json( + &connector_req, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(bluesnap_req)) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, + )?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("BluesnapPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - types::ResponseRouterData { + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, - } - .try_into() + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -760,3 +978,31 @@ impl api::IncomingWebhook for Bluesnap { Ok(res_json) } } + +impl services::ConnectorRedirectResponse for Bluesnap { + fn get_flow_type( + &self, + _query_params: &str, + json_payload: Option<serde_json::Value>, + _action: services::PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + let redirection_response: bluesnap::BluesnapRedirectionResponse = json_payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "json_payload", + })? + .parse_value("BluesnapRedirectionResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let redirection_result: bluesnap::BluesnapThreeDsResult = redirection_response + .authentication_response + .parse_struct("BluesnapThreeDsResult") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + match redirection_result.status.as_str() { + "Success" => Ok(payments::CallConnectorAction::Trigger), + _ => Ok(payments::CallConnectorAction::StatusUpdate( + enums::AttemptStatus::AuthenticationFailed, + )), + } + } +} diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index c2f851ce61e..aef423be6e2 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -1,4 +1,8 @@ use base64::Engine; +use common_utils::{ + ext_traits::{StringExt, ValueExt}, + pii::Email, +}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; @@ -19,6 +23,13 @@ pub struct BluesnapPaymentsRequest { payment_method: PaymentMethodDetails, currency: enums::Currency, card_transaction_type: BluesnapTxnType, + three_d_secure: Option<BluesnapThreeDSecureInfo>, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapThreeDSecureInfo { + three_d_secure_reference_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] @@ -116,10 +127,82 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { payment_method, currency: item.request.currency, card_transaction_type: auth_mode, + three_d_secure: None, + }) + } +} + +impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for BluesnapPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { + let redirection_response: BluesnapRedirectionResponse = item + .request + .payload + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.payload", + })? + .parse_value("BluesnapRedirectionResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let redirection_result: BluesnapThreeDsResult = redirection_response + .authentication_response + .parse_struct("BluesnapThreeDsResult") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let auth_mode = match item.request.capture_method { + Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, + _ => BluesnapTxnType::AuthCapture, + }; + let payment_method = if let Some(api::PaymentMethodData::Card(ccard)) = + item.request.payment_method_data.clone() + { + PaymentMethodDetails::CreditCard(Card { + card_number: ccard.card_number, + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.card_exp_year.clone(), + security_code: ccard.card_cvc, + }) + } else { + Err(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.payment_method_data", + })? + }; + Ok(Self { + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + payment_method, + currency: item.request.currency, + card_transaction_type: auth_mode, + three_d_secure: Some(BluesnapThreeDSecureInfo { + three_d_secure_reference_id: redirection_result + .three_d_secure + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "three_d_secure_reference_id", + })? + .three_d_secure_reference_id, + }), }) } } +#[derive(Debug, Deserialize, PartialEq)] +pub struct BluesnapRedirectionResponse { + pub authentication_response: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapThreeDsResult { + three_d_secure: Option<BluesnapThreeDsReference>, + pub status: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapThreeDsReference { + three_d_secure_reference_id: String, +} + #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BluesnapVoidRequest { @@ -181,6 +264,49 @@ impl TryFrom<&types::ConnectorAuthType> for BluesnapAuthType { } } } + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapCustomerRequest { + email: Option<Email>, +} + +impl TryFrom<&types::ConnectorCustomerRouterData> for BluesnapCustomerRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { + Ok(Self { + email: item.request.email.to_owned(), + }) + } +} + +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapCustomerResponse { + vaulted_shopper_id: u64, +} +impl<F, T> + TryFrom<types::ResponseRouterData<F, BluesnapCustomerResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BluesnapCustomerResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id: item.response.vaulted_shopper_id.to_string(), + }), + ..item.data + }) + } +} + // PaymentsResponse #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index ec1d76ffd67..d47bb0cc071 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -18,7 +18,7 @@ use crate::{ core::errors::{self, CustomResult}, pii::PeekInterface, types::{self, api, PaymentsCancelData, ResponseId}, - utils::{OptionExt, ValueExt}, + utils::{self, OptionExt, ValueExt}, }; pub fn missing_field_err( @@ -63,6 +63,7 @@ pub trait RouterData { fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<String, Error>; fn get_customer_id(&self) -> Result<String, Error>; + fn get_connector_customer_id(&self) -> Result<String, Error>; } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { @@ -151,6 +152,11 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .to_owned() .ok_or_else(missing_field_err("customer_id")) } + fn get_connector_customer_id(&self) -> Result<String, Error> { + self.connector_customer + .to_owned() + .ok_or_else(missing_field_err("connector_customer_id")) + } } pub trait PaymentsAuthorizeRequestData { @@ -560,8 +566,20 @@ pub fn get_header_key_value<'a>( key: &str, headers: &'a actix_web::http::header::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { - headers - .get(key) + get_header_field(headers.get(key)) +} + +pub fn get_http_header<'a>( + key: &str, + headers: &'a http::HeaderMap, +) -> CustomResult<&'a str, errors::ConnectorError> { + get_header_field(headers.get(key)) +} + +fn get_header_field( + field: Option<&http::HeaderValue>, +) -> CustomResult<&str, errors::ConnectorError> { + field .map(|header_value| { header_value .to_str() @@ -640,27 +658,16 @@ pub fn to_currency_base_unit( amount: i64, currency: storage_models::enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { - let amount_f64 = to_currency_base_unit_asf64(amount, currency)?; - Ok(format!("{amount_f64:.2}")) + utils::to_currency_base_unit(amount, currency) + .change_context(errors::ConnectorError::RequestEncodingFailed) } pub fn to_currency_base_unit_asf64( amount: i64, currency: storage_models::enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { - let amount_u32 = u32::try_from(amount) - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let amount_f64 = f64::from(amount_u32); - let amount = match currency { - storage_models::enums::Currency::JPY | storage_models::enums::Currency::KRW => amount_f64, - storage_models::enums::Currency::BHD - | storage_models::enums::Currency::JOD - | storage_models::enums::Currency::KWD - | storage_models::enums::Currency::OMR => amount_f64 / 1000.00, - _ => amount_f64 / 100.00, - }; - Ok(amount) + utils::to_currency_base_unit_asf64(amount, currency) + .change_context(errors::ConnectorError::RequestEncodingFailed) } pub fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index ce71849c097..eb06a09400c 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -299,6 +299,8 @@ pub enum ConnectorError { MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, + #[error("Missing 3DS redirection payload: {field_name}")] + MissingConnectorRedirectionPayload { field_name: &'static str }, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a292e4503fe..a03725b45fa 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -117,9 +117,16 @@ where get_connector_tokenization_action(state, &operation, payment_data, &validate_result) .await?; + let connector_string = connector + .as_ref() + .and_then(|connector_type| match connector_type { + api::ConnectorCallType::Single(connector) => Some(connector.connector_name.to_string()), + _ => None, + }); + let updated_customer = call_create_connector_customer( state, - &payment_data.payment_attempt.connector.clone(), + &connector_string, &customer, &merchant_account, &mut payment_data, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 27b69dcffed..03d578daeaf 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -107,7 +107,6 @@ default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, connector::Authorizedotnet, - connector::Bluesnap, connector::Braintree, connector::Checkout, connector::Coinbase, @@ -153,7 +152,6 @@ default_imp_for_create_customer!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, - connector::Bluesnap, connector::Braintree, connector::Checkout, connector::Coinbase, @@ -203,7 +201,6 @@ default_imp_for_connector_redirect_response!( connector::Aci, connector::Adyen, connector::Authorizedotnet, - connector::Bluesnap, connector::Braintree, connector::Coinbase, connector::Cybersource, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 5a4fd81bb2b..40c155c1478 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -126,7 +126,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f mandate_id: None, connector_response, setup_mandate: None, - token: None, + token: payment_attempt.payment_token.clone(), address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.foreign_into()), billing: billing_address.as_ref().map(|a| a.foreign_into()), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 53948e7af02..aad3b120793 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -18,7 +18,7 @@ use crate::{ storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, - utils::{OptionExt, ValueExt}, + utils::{self, OptionExt, ValueExt}, }; #[instrument(skip_all)] @@ -254,8 +254,12 @@ where let currency = payment_attempt .currency .as_ref() - .get_required_value("currency")? - .to_string(); + .get_required_value("currency")?; + let amount = utils::to_currency_base_unit(payment_attempt.amount, *currency).change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "amount", + }, + )?; let mandate_id = payment_attempt.mandate_id.clone(); let refunds_response = if refunds.is_empty() { None @@ -269,7 +273,12 @@ where let redirection_data = redirection_data.get_required_value("redirection_data")?; let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; - services::ApplicationResponse::Form(form) + services::ApplicationResponse::Form(Box::new(services::RedirectionFormData { + redirect_form: form, + payment_method_data, + amount, + currency: currency.to_string(), + })) } else { let mut next_action_response = None; if payment_intent.status == enums::IntentStatus::RequiresCustomerAction { @@ -317,7 +326,7 @@ where .set_connector(routed_through) .set_client_secret(payment_intent.client_secret.map(masking::Secret::new)) .set_created(Some(payment_intent.created_at)) - .set_currency(currency) + .set_currency(currency.to_string()) .set_customer_id(customer.as_ref().map(|cus| cus.clone().customer_id)) .set_email( customer @@ -404,7 +413,7 @@ where amount_received: payment_intent.amount_captured, client_secret: payment_intent.client_secret.map(masking::Secret::new), created: Some(payment_intent.created_at), - currency, + currency: currency.to_string(), customer_id: payment_intent.customer_id, description: payment_intent.description, refunds: refunds_response, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index c0c30e9b883..ff2d10ddd49 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -12,7 +12,7 @@ use std::{ use actix_web::{body, HttpRequest, HttpResponse, Responder}; use common_utils::errors::ReportSwitchExt; use error_stack::{report, IntoReport, Report, ResultExt}; -use masking::{ExposeOptionInterface, PeekInterface}; +use masking::{ExposeInterface, ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use serde_json::json; @@ -182,6 +182,7 @@ where match call_connector_action { payments::CallConnectorAction::HandleResponse(res) => { let response = types::Response { + headers: None, response: res.into(), status_code: 200, }; @@ -377,6 +378,7 @@ async fn handle_response( .map(|response| async { logger::info!(?response); let status_code = response.status().as_u16(); + let headers = Some(response.headers().to_owned()); match status_code { 200..=202 | 302 | 204 => { logger::debug!(response=?response); @@ -389,6 +391,7 @@ async fn handle_response( .change_context(errors::ApiClientError::ResponseDecodingFailed) .attach_printable("Error while waiting for response")?; Ok(Ok(types::Response { + headers, response, status_code, })) @@ -408,6 +411,7 @@ async fn handle_response( // _ => errors::ApiClientError::UnexpectedServerResponse, // }; Ok(Err(types::Response { + headers, response: bytes, status_code, })) @@ -433,6 +437,7 @@ async fn handle_response( Err(report!(error).attach_printable("Client error response received")) */ Ok(Err(types::Response { + headers, response: bytes, status_code, })) @@ -451,10 +456,18 @@ pub enum ApplicationResponse<R> { StatusOk, TextPlain(String), JsonForRedirection(api::RedirectionResponse), - Form(RedirectForm), + Form(Box<RedirectionFormData>), FileData((Vec<u8>, mime::Mime)), } +#[derive(Debug, Eq, PartialEq)] +pub struct RedirectionFormData { + pub redirect_form: RedirectForm, + pub payment_method_data: Option<api::PaymentMethodData>, + pub amount: String, + pub currency: String, +} + #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, @@ -476,6 +489,9 @@ pub enum RedirectForm { Html { html_data: String, }, + BlueSnap { + payment_fields_token: String, // payment-field-token + }, } impl From<(url::Url, Method)> for RedirectForm { @@ -588,10 +604,14 @@ where ), } } - Ok(ApplicationResponse::Form(response)) => build_redirection_form(&response) - .respond_to(request) - .map_into_boxed_body(), - + Ok(ApplicationResponse::Form(redirection_data)) => build_redirection_form( + &redirection_data.redirect_form, + redirection_data.payment_method_data, + redirection_data.amount, + redirection_data.currency, + ) + .respond_to(request) + .map_into_boxed_body(), Err(error) => log_and_return_error_response(error), }; @@ -696,7 +716,12 @@ impl Authenticate for api_models::payments::PaymentsCancelRequest {} impl Authenticate for api_models::payments::PaymentsCaptureRequest {} impl Authenticate for api_models::payments::PaymentsStartRequest {} -pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup { +pub fn build_redirection_form( + form: &RedirectForm, + payment_method_data: Option<api_models::payments::PaymentMethodData>, + amount: String, + currency: String, +) -> maud::Markup { use maud::PreEscaped; match form { @@ -760,6 +785,75 @@ pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup { } }, RedirectForm::Html { html_data } => PreEscaped(html_data.to_string()), + RedirectForm::BlueSnap { + payment_fields_token, + } => { + let card_details = if let Some(api::PaymentMethodData::Card(ccard)) = + payment_method_data + { + format!( + "var newCard={{ccNumber: \"{}\",cvv: \"{}\",expDate: \"{}/{}\",amount: {},currency: \"{}\"}};", + ccard.card_number.expose(), + ccard.card_cvc.expose(), + ccard.card_exp_month.clone().expose(), + ccard.card_exp_year.expose(), + amount, + currency + ) + } else { + "".to_string() + }; + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + (PreEscaped(r#"<script src="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"></script>"#)) + } + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + + (PreEscaped(format!("<script> + bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\", + function(sdkResponse) {{ + console.log(sdkResponse); + var f = document.createElement('form'); + f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/bluesnap\"); + f.method='POST'; + var i=document.createElement('input'); + i.type='hidden'; + i.name='authentication_response'; + i.value=JSON.stringify(sdkResponse); + f.appendChild(i); + document.body.appendChild(f); + f.submit(); + }}); + {card_details} + bluesnap.threeDsPaymentsSubmitData(newCard); + </script> + "))) + }} + } } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index d67dd9f7b4e..53c84fc3a28 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -555,6 +555,7 @@ pub struct ConnectorsList { #[derive(Clone, Debug)] pub struct Response { + pub headers: Option<http::HeaderMap>, pub response: bytes::Bytes, pub status_code: u16, } diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 3104bc65ce6..4e3615d5f6f 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -119,3 +119,34 @@ impl<E> ConnectorResponseExt }) } } + +/// Convert the amount to its base denomination based on Currency and return String +pub fn to_currency_base_unit( + amount: i64, + currency: storage_models::enums::Currency, +) -> Result<String, error_stack::Report<errors::ValidationError>> { + let amount_f64 = to_currency_base_unit_asf64(amount, currency)?; + Ok(format!("{amount_f64:.2}")) +} + +/// Convert the amount to its base denomination based on Currency and return f64 +pub fn to_currency_base_unit_asf64( + amount: i64, + currency: storage_models::enums::Currency, +) -> Result<f64, error_stack::Report<errors::ValidationError>> { + let amount_u32 = u32::try_from(amount).into_report().change_context( + errors::ValidationError::InvalidValue { + message: amount.to_string(), + }, + )?; + let amount_f64 = f64::from(amount_u32); + let amount = match currency { + storage_models::enums::Currency::JPY | storage_models::enums::Currency::KRW => amount_f64, + storage_models::enums::Currency::BHD + | storage_models::enums::Currency::JOD + | storage_models::enums::Currency::KWD + | storage_models::enums::Currency::OMR => amount_f64 / 1000.00, + _ => amount_f64 / 100.00, + }; + Ok(amount) +}
feat
[Bluesnap] add cards 3DS support (#1057)
93dd60c9ab8180ed7688959e32a3c2730c2bfad2
2024-07-19 10:30:51
github-actions
chore(postman): update Postman collection files
false
diff --git a/postman/collection-json/adyen_uk.postman_collection.json b/postman/collection-json/adyen_uk.postman_collection.json index bae84c62f2a..7b4f9b0a7da 100644 --- a/postman/collection-json/adyen_uk.postman_collection.json +++ b/postman/collection-json/adyen_uk.postman_collection.json @@ -728,7 +728,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_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\"}},\"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\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\"}},\"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", @@ -1313,7 +1313,7 @@ "language": "json" } }, - "raw": "{\"amount\":1100,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1100,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"gift_card\",\"payment_method_type\":\"givex\",\"payment_method_data\":{\"gift_card\":{\"givex\":{\"number\":\"6364530000000000\",\"cvc\":\"122222\"}}},\"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\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":1100,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1100,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"gift_card\",\"payment_method_type\":\"givex\",\"payment_method_data\":{\"gift_card\":{\"givex\":{\"number\":\"6364530000000000\",\"cvc\":\"122222\"}}},\"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", @@ -11093,7 +11093,7 @@ "language": "json" } }, - "raw": "{\"amount\":14100,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":14100,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"gift_card\",\"payment_method_type\":\"givex\",\"payment_method_data\":{\"gift_card\":{\"givex\":{\"number\":\"6364530000000000\",\"cvc\":\"122222\"}}},\"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\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":14100,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":14100,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"gift_card\",\"payment_method_type\":\"givex\",\"payment_method_data\":{\"gift_card\":{\"givex\":{\"number\":\"6364530000000000\",\"cvc\":\"122222\"}}},\"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", diff --git a/postman/collection-json/authorizedotnet.postman_collection.json b/postman/collection-json/authorizedotnet.postman_collection.json index b07503cd37f..00ecaec2260 100644 --- a/postman/collection-json/authorizedotnet.postman_collection.json +++ b/postman/collection-json/authorizedotnet.postman_collection.json @@ -974,7 +974,7 @@ "language": "json" } }, - "raw": "{\"amount\":7003,\"currency\":\"USD\",\"confirm\":true,\"routing\":{\"data\":\"authorizedotnet\",\"type\":\"single\"},\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"370000000000002\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"900\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":7003,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"370000000000002\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"900\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -2436,7 +2436,7 @@ "language": "json" } }, - "raw": "{\"amount\":7003,\"currency\":\"USD\",\"confirm\":true,\"routing\":{\"data\":\"authorizedotnet\",\"type\":\"single\"},\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"370000000000002\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"900\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":7003,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"370000000000002\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"900\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/bankofamerica.postman_collection.json b/postman/collection-json/bankofamerica.postman_collection.json index e36d7f915aa..2a3238bb8fd 100644 --- a/postman/collection-json/bankofamerica.postman_collection.json +++ b/postman/collection-json/bankofamerica.postman_collection.json @@ -2186,7 +2186,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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\":\"bankofamerica\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -2424,7 +2424,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"24\",\"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,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"24\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -2675,7 +2675,7 @@ "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"24\",\"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\":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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"24\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -3125,7 +3125,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"abcd\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"abcd\"}},\"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\":\"bankofamerica\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"abcd\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"abcd\"}},\"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", @@ -3525,7 +3525,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"3566111111111113\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"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,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"3566111111111113\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -3917,7 +3917,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"3566111111111113\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"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,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"3566111111111113\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json index bbbc1d7859a..7f83829a35d 100644 --- a/postman/collection-json/bluesnap.postman_collection.json +++ b/postman/collection-json/bluesnap.postman_collection.json @@ -4338,7 +4338,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/checkout.postman_collection.json b/postman/collection-json/checkout.postman_collection.json index b0f120bc33c..1eee3ce8522 100644 --- a/postman/collection-json/checkout.postman_collection.json +++ b/postman/collection-json/checkout.postman_collection.json @@ -9039,7 +9039,7 @@ "language": "json" } }, - "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"checkout\"}}" + "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"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", @@ -9936,7 +9936,7 @@ "language": "json" } }, - "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"checkout\"}}" + "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"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", @@ -10439,7 +10439,7 @@ "language": "json" } }, - "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"checkout\"}}" + "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"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", @@ -10958,7 +10958,7 @@ "language": "json" } }, - "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"checkout\"}}" + "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}},\"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", @@ -11309,7 +11309,7 @@ "language": "json" } }, - "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"checkout\"}}" + "raw": "{\"amount\":6000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"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\"}},\"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", diff --git a/postman/collection-json/cybersource.postman_collection.json b/postman/collection-json/cybersource.postman_collection.json index 13971702301..b877aaa5636 100644 --- a/postman/collection-json/cybersource.postman_collection.json +++ b/postman/collection-json/cybersource.postman_collection.json @@ -7232,7 +7232,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\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"},\"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\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", diff --git a/postman/collection-json/forte.postman_collection.json b/postman/collection-json/forte.postman_collection.json index 79e0bd07bf2..95e5b82f796 100644 --- a/postman/collection-json/forte.postman_collection.json +++ b/postman/collection-json/forte.postman_collection.json @@ -516,7 +516,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"routing\":{\"type\":\"single\",\"data\":\"forte\"},\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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", @@ -745,7 +745,7 @@ "language": "json" } }, - "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"routing\":{\"type\":\"single\",\"data\":\"forte\"},\"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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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", diff --git a/postman/collection-json/hyperswitch.postman_collection.json b/postman/collection-json/hyperswitch.postman_collection.json index 7c199c9e475..14e280c7c6c 100644 --- a/postman/collection-json/hyperswitch.postman_collection.json +++ b/postman/collection-json/hyperswitch.postman_collection.json @@ -10211,7 +10211,7 @@ "language": "json" } }, - "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"routing\":{\"type\":\"single\",\"data\":\"stripe\"},\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" + "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/multisafepay.postman_collection.json b/postman/collection-json/multisafepay.postman_collection.json index fe8efb5ad0f..66ea1f65ffc 100644 --- a/postman/collection-json/multisafepay.postman_collection.json +++ b/postman/collection-json/multisafepay.postman_collection.json @@ -525,7 +525,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"someone\",\"last_name\":\"happy\"}},\"routing\":{\"type\":\"single\",\"data\":\"multisafepay\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"someone\",\"last_name\":\"happy\"}},\"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\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"someone\",\"last_name\":\"happy\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"someone\",\"last_name\":\"happy\"}},\"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", @@ -2078,7 +2078,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"routing\":{\"type\":\"single\",\"data\":\"multisafepay\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"someone\",\"last_name\":\"happy\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"someone\",\"last_name\":\"happy\"}},\"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\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"someone\",\"last_name\":\"happy\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"someone\",\"last_name\":\"happy\"}},\"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", diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json index 1e48b4a8646..49a99fe3ffe 100644 --- a/postman/collection-json/nmi.postman_collection.json +++ b/postman/collection-json/nmi.postman_collection.json @@ -9101,7 +9101,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"4111111111111111\",\"card_exp_month\":\"01\",\"card_exp_year\":\"69\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"4111111111111111\",\"card_exp_month\":\"01\",\"card_exp_year\":\"69\",\"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", @@ -9769,7 +9769,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"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\"},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"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", @@ -12321,7 +12321,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":7000,\"currency\":\"USD\"}}},\"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\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":7000,\"currency\":\"USD\"}}},\"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\",\"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", diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json index 58368b3b856..58d9cec1c75 100644 --- a/postman/collection-json/paypal.postman_collection.json +++ b/postman/collection-json/paypal.postman_collection.json @@ -805,7 +805,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"surcharge_details\":{\"surcharge_amount\":5,\"tax_amount\":5},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"paypal\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"surcharge_details\":{\"surcharge_amount\":5,\"tax_amount\":5},\"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", diff --git a/postman/collection-json/prophetpay.postman_collection.json b/postman/collection-json/prophetpay.postman_collection.json index bd946301f55..0b8c0a5fe48 100644 --- a/postman/collection-json/prophetpay.postman_collection.json +++ b/postman/collection-json/prophetpay.postman_collection.json @@ -515,7 +515,7 @@ "language": "json" } }, - "raw": "{\"amount\":10000,\"currency\":\"USD\",\"confirm\":true,\"amount_to_capture\":10000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"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\"}}" + "raw": "{\"amount\":10000,\"currency\":\"USD\",\"confirm\":true,\"amount_to_capture\":10000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"return_url\":\"https://www.google.com\",\"payment_method\":\"card_redirect\",\"payment_method_type\":\"card_redirect\",\"payment_method_data\":{\"card_redirect\":{\"card_redirect\":{}}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -743,7 +743,7 @@ "language": "json" } }, - "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":true,\"amount_to_capture\":8000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"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\"}}" + "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":true,\"amount_to_capture\":8000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"return_url\":\"https://www.google.com\",\"payment_method\":\"card_redirect\",\"payment_method_type\":\"card_redirect\",\"payment_method_data\":{\"card_redirect\":{\"card_redirect\":{}}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -994,7 +994,7 @@ "language": "json" } }, - "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"amount_to_capture\":8000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"return_url\":\"https://www.google.com\",\"routing\":{\"type\":\"single\",\"data\":\"prophetpay\"}}" + "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"amount_to_capture\":8000,\"business_country\":\"US\",\"customer_id\":\"not_a_rick_roll\",\"return_url\":\"https://www.google.com\"}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 0f7aa535a72..c6331002fe3 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -2493,7 +2493,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"country_code\":\"+91\"},\"email\":\"[email protected]\"},\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"country_code\":\"+91\"},\"email\":\"[email protected]\"},\"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\":\"9123456789\",\"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\":{\"connector\":\"stripe\",\"merchant_connector_id\":\"{{merchant_connector_id}}\"}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -2757,7 +2757,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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\":{\"connector\":\"stripe\",\"merchant_connector_id\":\"{{merchant_connector_id}}\"}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -3593,7 +3593,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\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -4295,7 +4295,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -4542,7 +4542,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -4825,7 +4825,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -5454,7 +5454,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\":\"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\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -6040,7 +6040,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -6846,7 +6846,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}},\"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\"},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}},\"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\"},\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -7915,7 +7915,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -8315,7 +8315,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -8707,7 +8707,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9099,7 +9099,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9467,7 +9467,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\":\"[email protected]\",\"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\",\"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\":{\"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\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"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\":{\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9709,7 +9709,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\":\"[email protected]\",\"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": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -10148,7 +10148,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":{\"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,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":{\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -10419,7 +10419,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -10850,7 +10850,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -11620,7 +11620,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\":\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\":\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -11897,7 +11897,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -12181,7 +12181,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -12468,7 +12468,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -12915,7 +12915,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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", @@ -13345,7 +13345,7 @@ "language": "json" } }, - "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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\":\"ES\"},\"email\":\"[email protected]\"},\"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\":\"[email protected]\",\"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\":\"ES\"},\"email\":\"[email protected]\"},\"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}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -13775,7 +13775,7 @@ "language": "json" } }, - "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -14205,7 +14205,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\":\"[email protected]\",\"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\":\"NL\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\":\"[email protected]\",\"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\":\"NL\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -14635,7 +14635,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\":\"[email protected]\",\"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\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15065,7 +15065,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\":\"[email protected]\",\"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\":\"AT\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\":\"[email protected]\",\"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\":\"AT\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15495,7 +15495,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"HarrisonStreet\",\"line3\":\"HarrisonStreet\",\"city\":\"SanFransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Swangi\",\"last_name\":\"Kumari\"},\"email\":\"[email protected]\"},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"HarrisonStreet\",\"line3\":\"HarrisonStreet\",\"city\":\"SanFransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Swangi\",\"last_name\":\"Kumari\"},\"email\":\"[email protected]\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15945,7 +15945,7 @@ "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\":\"[email protected]\",\"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\"}}},\"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\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"[email protected]\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"HarrisonStreet\",\"line3\":\"HarrisonStreet\",\"city\":\"SanFransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Swangi\",\"last_name\":\"Kumari\"}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\"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\":\"[email protected]\",\"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\"}}},\"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\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"[email protected]\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"HarrisonStreet\",\"line3\":\"HarrisonStreet\",\"city\":\"SanFransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Swangi\",\"last_name\":\"Kumari\"}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -16187,7 +16187,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\":\"[email protected]\",\"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\":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\":\"[email protected]\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -16611,7 +16611,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -17215,7 +17215,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -17627,7 +17627,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\":\"stripesavecard_1234\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"},\"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\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"stripesavecard_1234\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -17827,7 +17827,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\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"},\"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\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -18341,7 +18341,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\":\"stripesavecard_1234\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"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\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"stripesavecard_1234\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -18541,7 +18541,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\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"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\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -18807,7 +18807,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\":\"adyensavecard\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"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\":\"9123456789\",\"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\":\"9123456789\",\"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,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"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\":{\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -19161,7 +19161,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"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\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"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\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -19967,7 +19967,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":{\"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": "{\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":{\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -20227,7 +20227,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\":\"[email protected]\",\"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\",\"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\":{\"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\",\"business_country\":\"US\",\"business_label\":\"default\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"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\":{\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -20485,7 +20485,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\"}},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\"}},\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -20732,7 +20732,7 @@ "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -22279,7 +22279,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -22781,7 +22781,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"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\":\"united states\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"united states\"}},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"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\":\"united states\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"united states\"}},\"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", @@ -22904,7 +22904,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"2023\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"2023\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -23037,7 +23037,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2022\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2022\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -23160,7 +23160,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -23283,7 +23283,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -23573,7 +23573,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -23953,7 +23953,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -24214,7 +24214,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -24471,7 +24471,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\":\"[email protected]\",\"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": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -24851,7 +24851,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -25188,7 +25188,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -25551,7 +25551,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\":\"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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"}}},\"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\":\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -25812,7 +25812,7 @@ "language": "json" } }, - "raw": "{\"amount\":8040,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"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\":8040,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"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\"}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/postman/collection-json/volt.postman_collection.json b/postman/collection-json/volt.postman_collection.json index c34d77fea03..3b996480472 100644 --- a/postman/collection-json/volt.postman_collection.json +++ b/postman/collection-json/volt.postman_collection.json @@ -516,7 +516,7 @@ "language": "json" } }, - "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"volt\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -754,7 +754,7 @@ "language": "json" } }, - "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"volt\"}}" + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -1005,7 +1005,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"volt\"}}" + "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"open_banking_uk\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"citi\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"9123456789\",\"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\":\"9123456789\",\"country_code\":\"+91\"}},\"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", @@ -1454,7 +1454,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"singh\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"volt\"}}" + "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"singh\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -1854,7 +1854,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"singh\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"volt\"}}" + "raw": "{\"amount\":6540,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"singh\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "url": { "raw": "{{baseUrl}}/payments",
chore
update Postman collection files
f12abbcef4d090c77944729cc5e983c1a2e6a14f
2023-02-28 19:15:25
saiharsha-juspay
feat(router): added incoming refund webhooks flow (#683)
false
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 5120d92c98c..ef42c72716f 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -264,6 +264,8 @@ pub enum Currency { #[strum(serialize_all = "snake_case")] pub enum EventType { PaymentSucceeded, + RefundSucceeded, + RefundFailed, } #[derive( diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index d3ae9ea0d6c..5be508abedb 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -2,13 +2,15 @@ use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as api_enums, payments}; +use crate::{enums as api_enums, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { PaymentIntentFailure, PaymentIntentSuccess, + RefundFailure, + RefundSuccess, EndpointVerification, } @@ -24,6 +26,8 @@ impl From<IncomingWebhookEvent> for WebhookFlow { match evt { IncomingWebhookEvent::PaymentIntentFailure => Self::Payment, IncomingWebhookEvent::PaymentIntentSuccess => Self::Payment, + IncomingWebhookEvent::RefundSuccess => Self::Refund, + IncomingWebhookEvent::RefundFailure => Self::Refund, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, } } @@ -56,4 +60,5 @@ pub struct OutgoingWebhook { #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum OutgoingWebhookContent { PaymentDetails(payments::PaymentsResponse), + RefundDetails(refunds::RefundResponse), } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 79acad0b0b3..be8f01c0d13 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -733,11 +733,7 @@ impl api::IncomingWebhook for Adyen { ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - - Ok(match notif.event_code.as_str() { - "AUTHORISATION" => api::IncomingWebhookEvent::PaymentIntentSuccess, - _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?, - }) + Ok(notif.event_code.into()) } fn get_webhook_resource_object( diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 4eff65179fb..d91bd37b7df 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,3 +1,4 @@ +use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use error_stack::ResultExt; use masking::PeekInterface; @@ -1168,6 +1169,27 @@ pub struct AdyenAmountWH { pub currency: String, } +#[derive(Debug, Deserialize, strum::Display)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] +pub enum WebhookEventCode { + Authorisation, + Refund, + CancelOrRefund, + RefundFailed, +} + +impl From<WebhookEventCode> for IncomingWebhookEvent { + fn from(code: WebhookEventCode) -> Self { + match code { + WebhookEventCode::Authorisation => Self::PaymentIntentSuccess, + WebhookEventCode::Refund => Self::RefundSuccess, + WebhookEventCode::CancelOrRefund => Self::RefundSuccess, + WebhookEventCode::RefundFailed => Self::RefundFailure, + } + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenNotificationRequestItemWH { @@ -1175,7 +1197,7 @@ pub struct AdyenNotificationRequestItemWH { pub amount: AdyenAmountWH, pub original_reference: Option<String>, pub psp_reference: String, - pub event_code: String, + pub event_code: WebhookEventCode, pub merchant_account_code: String, pub merchant_reference: String, pub success: String, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index bf462552eb0..c4eaf3653bb 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -400,6 +400,8 @@ pub enum WebhooksFlowError { MerchantWebhookURLNotConfigured, #[error("Payments core flow failed")] PaymentsCoreFailed, + #[error("Refunds core flow failed")] + RefundsCoreFailed, #[error("Webhook event creation failed")] WebhookEventCreationFailed, #[error("Unable to fork webhooks flow for outgoing webhooks")] @@ -408,6 +410,8 @@ pub enum WebhooksFlowError { CallToMerchantFailed, #[error("Webhook not received by merchant")] NotReceivedByMerchant, + #[error("Resource not found")] + ResourceNotFound, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 7be7781bd06..4df45c00cc8 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -9,7 +9,7 @@ use crate::{ consts, core::{ errors::{self, CustomResult, RouterResponse}, - payments, + payments, refunds, }, db::StorageInterface, logger, @@ -90,6 +90,87 @@ async fn payments_incoming_webhook_flow( Ok(()) } +#[instrument(skip_all)] +async fn refunds_incoming_webhook_flow( + state: AppState, + merchant_account: storage::MerchantAccount, + webhook_details: api::IncomingWebhookDetails, + connector_name: &str, + source_verified: bool, + event_type: api_models::webhooks::IncomingWebhookEvent, +) -> CustomResult<(), errors::WebhooksFlowError> { + let db = &*state.store; + //find refund by connector refund id + let refund = db + .find_refund_by_merchant_id_connector_refund_id_connector( + &merchant_account.merchant_id, + &webhook_details.object_reference_id, + connector_name, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::WebhooksFlowError::ResourceNotFound) + .attach_printable_lazy(|| "Failed fetching the refund")?; + let refund_id = refund.refund_id.to_owned(); + //if source verified then update refund status else trigger refund sync + let updated_refund = if source_verified { + let refund_update = storage::RefundUpdate::StatusUpdate { + connector_refund_id: None, + sent_to_gateway: true, + refund_status: event_type + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::RefundsCoreFailed)?, + }; + state + .store + .update_refund( + refund.to_owned(), + refund_update, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::WebhooksFlowError::RefundsCoreFailed) + .attach_printable_lazy(|| { + format!( + "Failed while updating refund: refund_id: {}", + refund_id.to_owned() + ) + })? + } else { + refunds::refund_retrieve_core(&state, merchant_account.clone(), refund_id.to_owned()) + .await + .change_context(errors::WebhooksFlowError::RefundsCoreFailed) + .attach_printable_lazy(|| { + format!( + "Failed while updating refund: refund_id: {}", + refund_id.to_owned() + ) + })? + }; + let event_type: enums::EventType = updated_refund + .refund_status + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::RefundsCoreFailed)?; + let refund_response: api_models::refunds::RefundResponse = updated_refund + .foreign_try_into() + .into_report() + .change_context(errors::WebhooksFlowError::RefundsCoreFailed)?; + create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + event_type, + enums::EventClass::Refunds, + None, + refund_id, + enums::EventObjectType::RefundDetails, + api::OutgoingWebhookContent::RefundDetails(refund_response), + ) + .await?; + Ok(()) +} + #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn create_event_and_trigger_outgoing_webhook( @@ -272,7 +353,7 @@ pub async fn webhooks_core( )?, }; - let flow_type: api::WebhookFlow = event_type.into(); + let flow_type: api::WebhookFlow = event_type.to_owned().into(); match flow_type { api::WebhookFlow::Payment => payments_incoming_webhook_flow( state.clone(), @@ -284,6 +365,18 @@ pub async fn webhooks_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming webhook flow for payments failed")?, + api::WebhookFlow::Refund => refunds_incoming_webhook_flow( + state.clone(), + merchant_account, + webhook_details, + connector_name, + source_verified, + event_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Incoming webhook flow for refunds failed")?, + api::WebhookFlow::ReturnResponse => {} _ => Err(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index e5f76736f10..732b932a1f1 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -36,6 +36,14 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + async fn find_refund_by_merchant_id_connector_refund_id_connector( + &self, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError>; + async fn update_refund( &self, this: storage_types::Refund, @@ -149,6 +157,25 @@ mod storage { .into_report() } + async fn find_refund_by_merchant_id_connector_refund_id_connector( + &self, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = pg_connection(&self.master_pool).await?; + storage_types::Refund::find_by_merchant_id_connector_refund_id_connector( + &conn, + merchant_id, + connector_refund_id, + connector, + ) + .await + .map_err(Into::into) + .into_report() + } + // async fn find_refund_by_payment_id_merchant_id_refund_id( // &self, // payment_id: &str, @@ -311,7 +338,7 @@ mod storage { Ok(HsetnxReply::KeySet) => { let conn = pg_connection(&self.master_pool).await?; - let reverse_lookups = vec![ + let mut reverse_lookups = vec![ storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( @@ -329,10 +356,25 @@ mod storage { created_refund.merchant_id, created_refund.internal_reference_id ), - pk_id: key, + pk_id: key.clone(), source: "refund".to_string(), }, ]; + if let Some(connector_refund_id) = + created_refund.to_owned().connector_refund_id + { + reverse_lookups.push(storage_types::ReverseLookupNew { + sk_id: field.clone(), + lookup_id: format!( + "{}_{}_{}", + created_refund.merchant_id, + connector_refund_id, + created_refund.connector + ), + pk_id: key, + source: "refund".to_string(), + }) + }; storage_types::ReverseLookupNew::batch_insert(reverse_lookups, &conn) .await .change_context(errors::StorageError::KVError)?; @@ -495,6 +537,47 @@ mod storage { } } + async fn find_refund_by_merchant_id_connector_refund_id_connector( + &self, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let database_call = || async { + let conn = pg_connection(&self.master_pool).await?; + storage_types::Refund::find_by_merchant_id_connector_refund_id_connector( + &conn, + merchant_id, + connector_refund_id, + connector, + ) + .await + .map_err(Into::into) + .into_report() + }; + match storage_scheme { + enums::MerchantStorageScheme::PostgresOnly => database_call().await, + enums::MerchantStorageScheme::RedisKv => { + let lookup_id = format!("{merchant_id}_{connector_refund_id}_{connector}"); + let lookup = self + .get_lookup_by_lookup_id(&lookup_id) + .await + .map_err(Into::<errors::StorageError>::into) + .into_report()?; + + let key = &lookup.pk_id; + db_utils::try_redis_get_else_try_database_get( + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), + database_call, + ) + .await + } + } + } + // async fn find_refund_by_payment_id_merchant_id_refund_id( // &self, // payment_id: &str, @@ -661,6 +744,28 @@ impl RefundInterface for MockDb { }) } + async fn find_refund_by_merchant_id_connector_refund_id_connector( + &self, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let refunds = self.refunds.lock().await; + + refunds + .iter() + .find(|refund| { + refund.merchant_id == merchant_id + && refund.connector_refund_id == Some(connector_refund_id.to_string()) + && refund.connector == connector + }) + .cloned() + .ok_or_else(|| { + errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() + }) + } + async fn find_refund_by_payment_id_merchant_id( &self, _payment_id: &str, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index b9a55b5b994..4bcc9fd7862 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -214,6 +214,40 @@ impl TryFrom<F<api_enums::IntentStatus>> for F<storage_enums::EventType> { } } +impl TryFrom<F<storage_enums::RefundStatus>> for F<storage_enums::EventType> { + type Error = errors::ValidationError; + + fn try_from(value: F<storage_enums::RefundStatus>) -> Result<Self, Self::Error> { + match value.0 { + storage_enums::RefundStatus::Success => Ok(storage_enums::EventType::RefundSucceeded), + storage_enums::RefundStatus::Failure => Ok(storage_enums::EventType::RefundFailed), + _ => Err(errors::ValidationError::IncorrectValueProvided { + field_name: "refund_status", + }), + } + .map(Into::into) + } +} + +impl TryFrom<F<api_models::webhooks::IncomingWebhookEvent>> for F<storage_enums::RefundStatus> { + type Error = errors::ValidationError; + + fn try_from(value: F<api_models::webhooks::IncomingWebhookEvent>) -> Result<Self, Self::Error> { + match value.0 { + api_models::webhooks::IncomingWebhookEvent::RefundSuccess => { + Ok(storage_enums::RefundStatus::Success) + } + api_models::webhooks::IncomingWebhookEvent::RefundFailure => { + Ok(storage_enums::RefundStatus::Failure) + } + _ => Err(errors::ValidationError::IncorrectValueProvided { + field_name: "incoming_webhook_event_type", + }), + } + .map(Into::into) + } +} + impl From<F<storage_enums::EventType>> for F<api_enums::EventType> { fn from(event_type: F<storage_enums::EventType>) -> Self { Self(frunk::labelled_convert_from(event_type.0)) diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index d822cfe1416..c7068fe9e36 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -272,6 +272,7 @@ pub enum Currency { #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, + Refunds, } #[derive( @@ -290,6 +291,7 @@ pub enum EventClass { #[strum(serialize_all = "snake_case")] pub enum EventObjectType { PaymentDetails, + RefundDetails, } #[derive( @@ -309,6 +311,8 @@ pub enum EventObjectType { #[strum(serialize_all = "snake_case")] pub enum EventType { PaymentSucceeded, + RefundSucceeded, + RefundFailed, } #[derive( diff --git a/crates/storage_models/src/query/refund.rs b/crates/storage_models/src/query/refund.rs index c6239b278ae..a9980af7f17 100644 --- a/crates/storage_models/src/query/refund.rs +++ b/crates/storage_models/src/query/refund.rs @@ -57,6 +57,23 @@ impl Refund { .await } + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_connector_refund_id_connector( + conn: &PgPooledConn, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::connector_refund_id.eq(connector_refund_id.to_owned())) + .and(dsl::connector.eq(connector.to_owned())), + ) + .await + } + #[instrument(skip(conn))] pub async fn find_by_internal_reference_id_merchant_id( conn: &PgPooledConn, diff --git a/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql b/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql new file mode 100644 index 00000000000..291a97c5ce1 --- /dev/null +++ b/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql @@ -0,0 +1 @@ +-- This file should undo anything in `up.sql` \ No newline at end of file diff --git a/migrations/2023-02-28-112730_add_refund_webhook_types/up.sql b/migrations/2023-02-28-112730_add_refund_webhook_types/up.sql new file mode 100644 index 00000000000..5a0f1a73cc3 --- /dev/null +++ b/migrations/2023-02-28-112730_add_refund_webhook_types/up.sql @@ -0,0 +1,8 @@ +-- Your SQL goes here +ALTER TYPE "EventClass" ADD VALUE 'refunds'; + +ALTER TYPE "EventObjectType" ADD VALUE 'refund_details'; + +ALTER TYPE "EventType" ADD VALUE 'refund_succeeded'; + +ALTER TYPE "EventType" ADD VALUE 'refund_failed'; \ No newline at end of file
feat
added incoming refund webhooks flow (#683)
acb329672297cd7337d0b0239e4c662257812e8a
2024-01-18 12:27:32
Swangi Kumari
refactor(connector): [Volt] Refactor Payments and Refunds Webhooks (#3377)
false
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs index 39296bb6434..f125f90d93a 100644 --- a/crates/router/src/connector/volt.rs +++ b/crates/router/src/connector/volt.rs @@ -635,43 +635,40 @@ impl api::IncomingWebhook for Volt { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - let x_volt_type = - utils::get_header_key_value(webhook_headers::X_VOLT_TYPE, request.headers)?; - if x_volt_type == "refund_confirmed" || x_volt_type == "refund_failed" { - let refund_webhook_body: volt::VoltRefundWebhookBodyReference = request - .body - .parse_struct("VoltRefundWebhookBodyReference") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - - let refund_reference = match refund_webhook_body.external_reference { - Some(external_reference) => { - api_models::webhooks::RefundIdType::RefundId(external_reference) - } - None => api_models::webhooks::RefundIdType::ConnectorRefundId( - refund_webhook_body.refund, - ), - }; - Ok(api_models::webhooks::ObjectReferenceId::RefundId( - refund_reference, - )) - } else { - let webhook_body: volt::VoltPaymentWebhookBodyReference = request - .body - .parse_struct("VoltPaymentWebhookBodyReference") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - let reference = match webhook_body.merchant_internal_reference { - Some(merchant_internal_reference) => { - api_models::payments::PaymentIdType::PaymentAttemptId( - merchant_internal_reference, - ) - } - None => api_models::payments::PaymentIdType::ConnectorTransactionId( - webhook_body.payment, - ), - }; - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - reference, - )) + let parsed_webhook_response = request + .body + .parse_struct::<volt::WebhookResponse>("VoltRefundWebhookBodyReference") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + match parsed_webhook_response { + volt::WebhookResponse::Payment(payment_response) => { + let reference = match payment_response.merchant_internal_reference { + Some(merchant_internal_reference) => { + api_models::payments::PaymentIdType::PaymentAttemptId( + merchant_internal_reference, + ) + } + None => api_models::payments::PaymentIdType::ConnectorTransactionId( + payment_response.payment, + ), + }; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + reference, + )) + } + volt::WebhookResponse::Refund(refund_response) => { + let refund_reference = match refund_response.external_reference { + Some(external_reference) => { + api_models::webhooks::RefundIdType::RefundId(external_reference) + } + None => api_models::webhooks::RefundIdType::ConnectorRefundId( + refund_response.refund, + ), + }; + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + refund_reference, + )) + } } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 8b9bbecb088..b1d77f3416f 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -46,7 +46,6 @@ pub mod webhook_headers { pub const X_VOLT_SIGNED: &str = "X-Volt-Signed"; pub const X_VOLT_TIMED: &str = "X-Volt-Timed"; pub const USER_AGENT: &str = "User-Agent"; - pub const X_VOLT_TYPE: &str = "X-Volt-Type"; } #[derive(Debug, Serialize)] @@ -488,6 +487,15 @@ pub struct VoltRefundWebhookBodyReference { pub external_reference: Option<String>, } +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum WebhookResponse { + // the enum order shouldn't be changed as this is being used during serialization and deserialization + Refund(VoltRefundWebhookBodyReference), + Payment(VoltPaymentWebhookBodyReference), +} + #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum VoltWebhookBodyEventType {
refactor
[Volt] Refactor Payments and Refunds Webhooks (#3377)
fc9057ef2c601fd8a7deb5d10dc5678abd8e6f7b
2023-07-07 12:10:49
Kartikeya Hegde
feat: add cache for api_key and mca tables (#1212)
false
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 3d1c2d6bb34..70e2cb99f92 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.rs @@ -1,6 +1,8 @@ use error_stack::IntoReport; use super::{MockDb, Store}; +#[cfg(feature = "accounts_cache")] +use crate::cache::{self, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, @@ -67,10 +69,46 @@ impl ApiKeyInterface for Store { api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) + let _merchant_id = merchant_id.clone(); + let _key_id = key_id.clone(); + let update_call = || async { + storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(not(feature = "accounts_cache"))] + { + update_call().await + } + + #[cfg(feature = "accounts_cache")] + { + use error_stack::report; + + // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id( + &conn, + &_merchant_id, + &_key_id, + ) .await .map_err(Into::into) - .into_report() + .into_report()? + .ok_or(report!(errors::StorageError::ValueNotFound(format!( + "ApiKey of {_key_id} not found" + ))))?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), + update_call, + ) + .await + } } async fn revoke_api_key( @@ -79,10 +117,41 @@ impl ApiKeyInterface for Store { key_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) + let delete_call = || async { + storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) + .await + .map_err(Into::into) + .into_report() + }; + #[cfg(not(feature = "accounts_cache"))] + { + delete_call().await + } + + #[cfg(feature = "accounts_cache")] + { + use error_stack::report; + + // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + + let api_key = + storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) + .await + .map_err(Into::into) + .into_report()? + .ok_or(report!(errors::StorageError::ValueNotFound(format!( + "ApiKey of {key_id} not found" + ))))?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), + delete_call, + ) .await - .map_err(Into::into) - .into_report() + } } async fn find_api_key_by_merchant_id_key_id_optional( @@ -101,11 +170,30 @@ impl ApiKeyInterface for Store { &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; - storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) + let _hashed_api_key = hashed_api_key.clone(); + let find_call = || async { + let conn = connection::pg_connection_read(self).await?; + storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(not(feature = "accounts_cache"))] + { + find_call().await + } + + #[cfg(feature = "accounts_cache")] + { + super::cache::get_or_populate_in_memory( + self, + &_hashed_api_key.into_inner(), + find_call, + &ACCOUNTS_CACHE, + ) .await - .map_err(Into::into) - .into_report() + } } async fn list_api_keys_by_merchant_id( @@ -288,7 +376,9 @@ mod tests { use time::macros::datetime; use crate::{ - db::{api_keys::ApiKeyInterface, MockDb}, + cache::{CacheKind, ACCOUNTS_CACHE}, + db::{api_keys::ApiKeyInterface, cache, MockDb}, + services::{PubSubInterface, RedisConnInterface}, types::storage, }; @@ -374,4 +464,67 @@ mod tests { 1 ); } + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_api_keys_cache() { + let db = MockDb::new(&Default::default()).await; + + let redis_conn = db.get_redis_conn(); + redis_conn + .subscribe("hyperswitch_invalidate") + .await + .unwrap(); + + let merchant_id = "test_merchant"; + let api = storage::ApiKeyNew { + key_id: "test_key".into(), + merchant_id: merchant_id.into(), + name: "My test key".into(), + description: None, + hashed_api_key: "a_hashed_key".to_string().into(), + prefix: "pre".into(), + created_at: datetime!(2023-06-01 0:00), + expires_at: None, + last_used: None, + }; + + let api = db.insert_api_key(api).await.unwrap(); + + let hashed_api_key = api.hashed_api_key.clone(); + let find_call = || async { + db.find_api_key_by_hash_optional(hashed_api_key.clone()) + .await + }; + let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory( + &db, + &format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .unwrap(); + + let delete_call = || async { db.revoke_api_key(merchant_id, &api.key_id).await }; + + cache::publish_and_redact( + &db, + CacheKind::Accounts( + format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()).into(), + ), + delete_call, + ) + .await + .unwrap(); + + assert!( + ACCOUNTS_CACHE + .get_val::<storage::ApiKey>(&format!( + "{}_{}", + merchant_id, + hashed_api_key.into_inner() + ),) + .is_none() + ) + } } diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index ce0e6cd5102..7727b76fd0f 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,9 +1,9 @@ use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "accounts_cache")] -use super::cache; use super::{MockDb, Store}; +#[cfg(feature = "accounts_cache")] +use crate::cache::{self, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, @@ -160,36 +160,13 @@ impl MerchantConnectorAccountInterface for Store { merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, - ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; - storage::MerchantConnectorAccount::find_by_merchant_id_connector( - &conn, - merchant_id, - connector_label, - ) - .await - .map_err(Into::into) - .into_report() - .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) - }) - .await - } - - async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( - &self, - merchant_id: &str, - merchant_connector_id: &str, - key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_connection_read(self).await?; - storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, - merchant_connector_id, + connector_label, ) .await .map_err(Into::into) @@ -207,14 +184,45 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - cache::get_or_populate_redis(self, merchant_connector_id, find_call) - .await? - .convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DeserializationFailed) + super::cache::get_or_populate_in_memory( + self, + &format!("{}_{}", merchant_id, connector_label), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .async_and_then(|item| async { + item.convert(key_store.key.get_inner()) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await } } + async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &self, + merchant_id: &str, + merchant_connector_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report() + .async_and_then(|item| async { + item.convert(key_store.key.get_inner()) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + } + async fn insert_merchant_connector_account( &self, t: domain::MerchantConnectorAccount, @@ -267,7 +275,9 @@ impl MerchantConnectorAccountInterface for Store { merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - let _merchant_connector_id = this.merchant_connector_id.clone(); + let _merchant_id = this.merchant_id.clone(); + let _merchant_connector_label = this.connector_label.clone(); + let update_call = || async { let conn = connection::pg_connection_write(self).await?; Conversion::convert(this) @@ -287,7 +297,14 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - cache::redact_cache(self, &_merchant_connector_id, update_call, None).await + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts( + format!("{}_{}", _merchant_id, _merchant_connector_label).into(), + ), + update_call, + ) + .await } #[cfg(not(feature = "accounts_cache"))] @@ -302,14 +319,47 @@ impl MerchantConnectorAccountInterface for Store { merchant_connector_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( - &conn, - merchant_id, - merchant_connector_id, - ) - .await - .map_err(Into::into) - .into_report() + let delete_call = || async { + storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report() + }; + + #[cfg(feature = "accounts_cache")] + { + // We need to fetch mca here because the key that's saved in cache in + // {merchant_id}_{connector_label}. + // Used function from storage model to reuse the connection that made here instead of + // creating new. + + let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( + &conn, + merchant_id, + merchant_connector_id, + ) + .await + .map_err(Into::into) + .into_report()?; + + super::cache::publish_and_redact( + self, + cache::CacheKind::Accounts( + format!("{}_{}", mca.merchant_id, mca.connector_label).into(), + ), + delete_call, + ) + .await + } + + #[cfg(not(feature = "accounts_cache"))] + { + delete_call().await + } } } @@ -507,3 +557,119 @@ impl MerchantConnectorAccountInterface for MockDb { } } } + +#[cfg(test)] +mod merchant_connector_account_cache_tests { + use api_models::enums::CountryAlpha2; + use common_utils::date_time; + use error_stack::ResultExt; + use storage_models::enums::ConnectorType; + + use crate::{ + cache::{CacheKind, ACCOUNTS_CACHE}, + core::errors, + db::{ + cache, merchant_connector_account::MerchantConnectorAccountInterface, + merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, + }, + services::{PubSubInterface, RedisConnInterface}, + types::{ + domain::{self, behaviour::Conversion, types as domain_types}, + storage, + }, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_connector_label_cache() { + let db = MockDb::new(&Default::default()).await; + + let redis_conn = db.get_redis_conn(); + let key = db.get_master_key(); + redis_conn + .subscribe("hyperswitch_invalidate") + .await + .unwrap(); + + let merchant_id = "test_merchant"; + let connector_label = "stripe_USA"; + let merchant_connector_id = "simple_merchant_connector_id"; + + let mca = domain::MerchantConnectorAccount { + id: Some(1), + merchant_id: merchant_id.to_string(), + connector_name: "stripe".to_string(), + connector_account_details: domain_types::encrypt( + serde_json::Value::default().into(), + key, + ) + .await + .unwrap(), + test_mode: None, + disabled: None, + merchant_connector_id: merchant_connector_id.to_string(), + payment_methods_enabled: None, + connector_type: ConnectorType::FinOperations, + metadata: None, + frm_configs: None, + connector_label: connector_label.to_string(), + business_country: CountryAlpha2::US, + business_label: "cloth".to_string(), + business_sub_label: None, + created_at: date_time::now(), + modified_at: date_time::now(), + }; + + let key_store = db + .get_merchant_key_store_by_merchant_id(merchant_id, &key.to_vec().into()) + .await + .unwrap(); + + db.insert_merchant_connector_account(mca, &key_store) + .await + .unwrap(); + let find_call = || async { + db.find_merchant_connector_account_by_merchant_id_connector_label( + merchant_id, + connector_label, + &key_store, + ) + .await + .unwrap() + .convert() + .await + .change_context(errors::StorageError::DecryptionError) + }; + let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( + &db, + &format!("{}_{}", merchant_id, connector_label), + find_call, + &ACCOUNTS_CACHE, + ) + .await + .unwrap(); + + let delete_call = || async { + db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id( + merchant_id, + merchant_connector_id, + ) + .await + }; + + cache::publish_and_redact( + &db, + CacheKind::Accounts(format!("{}_{}", merchant_id, connector_label).into()), + delete_call, + ) + .await + .unwrap(); + + assert!(ACCOUNTS_CACHE + .get_val::<domain::MerchantConnectorAccount>(&format!( + "{}_{}", + merchant_id, connector_label + ),) + .is_none()) + } +} diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs index 1df3cdd72dc..6608d4ed2fd 100644 --- a/crates/storage_models/src/api_keys.rs +++ b/crates/storage_models/src/api_keys.rs @@ -4,7 +4,7 @@ use time::PrimitiveDateTime; use crate::schema::api_keys; -#[derive(Debug, Clone, Identifiable, Queryable)] +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable)] #[diesel(table_name = api_keys, primary_key(key_id))] pub struct ApiKey { pub key_id: String, @@ -78,7 +78,7 @@ impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { } } -#[derive(Debug, Clone, AsExpression, PartialEq)] +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String);
feat
add cache for api_key and mca tables (#1212)
7fd79e05d54e6f135fbd4151d6638060660e6c85
2023-09-26 12:01:52
chikke srujan
refactor(connector): [Zen] Enhance currency Mapping with ConnectorCurrencyCommon Trait (#2196)
false
diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index 6bee7111b55..a284352bf42 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -78,6 +78,10 @@ impl ConnectorCommon for Zen { "zen" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } @@ -208,7 +212,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = zen::ZenPaymentsRequest::try_from(req)?; + let connector_router_data = zen::ZenRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = zen::ZenPaymentsRequest::try_from(&connector_router_data)?; let zen_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<zen::ZenPaymentsRequest>::encode_to_string_of_json, @@ -397,7 +407,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = zen::ZenRefundRequest::try_from(req)?; + let connector_router_data = zen::ZenRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = zen::ZenRefundRequest::try_from(&connector_router_data)?; let zen_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<zen::ZenRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 9182e370a4f..d13c9b6421f 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -16,6 +16,38 @@ use crate::{ types::{self, api, storage::enums, transformers::ForeignTryFrom}, utils::OptionExt, }; + +#[derive(Debug, Serialize)] +pub struct ZenRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for ZenRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + // Auth Struct pub struct ZenAuthType { pub(super) api_key: Secret<String>, @@ -171,14 +203,16 @@ pub struct WalletSessionData { pub pay_wall_secret: Option<String>, } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, &Card)> for ZenPaymentsRequest { +impl TryFrom<(&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card)> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: (&types::PaymentsAuthorizeRouterData, &Card)) -> Result<Self, Self::Error> { + fn try_from( + value: (&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card), + ) -> Result<Self, Self::Error> { let (item, ccard) = value; - let browser_info = item.request.get_browser_info()?; + let browser_info = item.router_data.request.get_browser_info()?; let ip = browser_info.get_ip_address()?; let browser_details = get_browser_details(&browser_info)?; - let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?; + let amount = item.amount.to_owned(); let payment_specific_data = ZenPaymentSpecificData::ZenOnetimePayment(Box::new(ZenPaymentData { browser_details, @@ -191,17 +225,22 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, &Card)> for ZenPaymentsReques .get_card_expiry_month_year_2_digit_with_delimiter("".to_owned()), cvv: ccard.card_cvc.clone(), }), - descriptor: item.get_description()?.chars().take(24).collect(), - return_verify_url: item.request.router_return_url.clone(), + descriptor: item + .router_data + .get_description()? + .chars() + .take(24) + .collect(), + return_verify_url: item.router_data.request.router_return_url.clone(), })); Ok(Self::ApiRequest(Box::new(ApiRequest { - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), payment_channel: ZenPaymentChannels::PclCard, - currency: item.request.currency, + currency: item.router_data.request.currency, payment_specific_data, - customer: get_customer(item, ip)?, - custom_ipn_url: item.request.get_webhook_url()?, - items: get_item_object(item, amount.clone())?, + customer: get_customer(item.router_data, ip)?, + custom_ipn_url: item.router_data.request.get_webhook_url()?, + items: get_item_object(item.router_data)?, amount, }))) } @@ -209,29 +248,26 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, &Card)> for ZenPaymentsReques impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::VoucherData, )> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::VoucherData, ), ) -> Result<Self, Self::Error> { let (item, voucher_data) = value; - let browser_info = item.request.get_browser_info()?; + let browser_info = item.router_data.request.get_browser_info()?; let ip = browser_info.get_ip_address()?; - let amount = utils::to_currency_base_unit_with_zero_decimal_check( - item.request.amount, - item.request.currency, - )?; + let amount = item.amount.to_owned(); let payment_specific_data = ZenPaymentSpecificData::ZenGeneralPayment(ZenGeneralPaymentData { //Connector Specific for Latam Methods payment_type: ZenPaymentTypes::General, - return_url: item.request.get_router_return_url()?, + return_url: item.router_data.request.get_router_return_url()?, }); let payment_channel = match voucher_data { api_models::payments::VoucherData::Boleto { .. } => { @@ -261,13 +297,13 @@ impl } }; Ok(Self::ApiRequest(Box::new(ApiRequest { - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), payment_channel, - currency: item.request.currency, + currency: item.router_data.request.currency, payment_specific_data, - customer: get_customer(item, ip)?, - custom_ipn_url: item.request.get_webhook_url()?, - items: get_item_object(item, amount.clone())?, + customer: get_customer(item.router_data, ip)?, + custom_ipn_url: item.router_data.request.get_webhook_url()?, + items: get_item_object(item.router_data)?, amount, }))) } @@ -275,26 +311,26 @@ impl impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Box<api_models::payments::BankTransferData>, )> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Box<api_models::payments::BankTransferData>, ), ) -> Result<Self, Self::Error> { let (item, bank_transfer_data) = value; - let browser_info = item.request.get_browser_info()?; + let browser_info = item.router_data.request.get_browser_info()?; let ip = browser_info.get_ip_address()?; - let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?; + let amount = item.amount.to_owned(); let payment_specific_data = ZenPaymentSpecificData::ZenGeneralPayment(ZenGeneralPaymentData { //Connector Specific for Latam Methods payment_type: ZenPaymentTypes::General, - return_url: item.request.get_router_return_url()?, + return_url: item.router_data.request.get_router_return_url()?, }); let payment_channel = match **bank_transfer_data { api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => { @@ -327,13 +363,13 @@ impl } }; Ok(Self::ApiRequest(Box::new(ApiRequest { - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), payment_channel, - currency: item.request.currency, + currency: item.router_data.request.currency, payment_specific_data, - customer: get_customer(item, ip)?, - custom_ipn_url: item.request.get_webhook_url()?, - items: get_item_object(item, amount.clone())?, + customer: get_customer(item.router_data, ip)?, + custom_ipn_url: item.router_data.request.get_webhook_url()?, + items: get_item_object(item.router_data)?, amount, }))) } @@ -421,19 +457,19 @@ impl impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, )> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, wallet_data): ( - &types::PaymentsAuthorizeRouterData, + &ZenRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, ), ) -> Result<Self, Self::Error> { - let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?; - let connector_meta = item.get_connector_meta()?; + let amount = item.amount.to_owned(); + let connector_meta = item.router_data.get_connector_meta()?; let session: SessionObject = connector_meta .parse_value("SessionObject") .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -489,15 +525,15 @@ impl .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; let mut checkout_request = CheckoutRequest { - merchant_transaction_id: item.connector_request_reference_id.clone(), + merchant_transaction_id: item.router_data.connector_request_reference_id.clone(), specified_payment_channel, - currency: item.request.currency, - custom_ipn_url: item.request.get_webhook_url()?, - items: get_item_object(item, amount.clone())?, + currency: item.router_data.request.currency, + custom_ipn_url: item.router_data.request.get_webhook_url()?, + items: get_item_object(item.router_data)?, amount, terminal_uuid: Secret::new(terminal_uuid), signature: None, - url_redirect: item.request.get_return_url()?, + url_redirect: item.router_data.request.get_return_url()?, }; checkout_request.signature = Some(get_checkout_signature(&checkout_request, &session_data)?); @@ -588,7 +624,6 @@ fn get_customer( fn get_item_object( item: &types::PaymentsAuthorizeRouterData, - _amount: String, ) -> Result<Vec<ZenItemObject>, error_stack::Report<errors::ConnectorError>> { let order_details = item.request.get_order_details()?; @@ -649,10 +684,12 @@ fn get_browser_details( }) } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for ZenPaymentsRequest { +impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match &item.request.payment_method_data { + fn try_from( + item: &ZenRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match &item.router_data.request.payment_method_data { api_models::payments::PaymentMethodData::Card(card) => Self::try_from((item, card)), api_models::payments::PaymentMethodData::Wallet(wallet_data) => { Self::try_from((item, wallet_data)) @@ -969,17 +1006,14 @@ pub struct ZenRefundRequest { merchant_transaction_id: String, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for ZenRefundRequest { +impl<F> TryFrom<&ZenRouterData<&types::RefundsRouterData<F>>> for ZenRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &ZenRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { - amount: utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, - )?, - transaction_id: item.request.connector_transaction_id.clone(), - currency: item.request.currency, - merchant_transaction_id: item.request.refund_id.clone(), + amount: item.amount.to_owned(), + transaction_id: item.router_data.request.connector_transaction_id.clone(), + currency: item.router_data.request.currency, + merchant_transaction_id: item.router_data.request.refund_id.clone(), }) } }
refactor
[Zen] Enhance currency Mapping with ConnectorCurrencyCommon Trait (#2196)
f2b88350a6cbe2708976564c532bcb9e47f54d68
2023-01-06 14:02:39
ItsMeShashank
feat(router): add payment failed webhook event (#305)
false
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index ddc4ffa13a8..eb116eba317 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -7,6 +7,7 @@ use crate::{enums as api_enums, payments}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { + PaymentIntentFailure, PaymentIntentSuccess, } @@ -19,6 +20,7 @@ pub enum WebhookFlow { impl From<IncomingWebhookEvent> for WebhookFlow { fn from(evt: IncomingWebhookEvent) -> Self { match evt { + IncomingWebhookEvent::PaymentIntentFailure => Self::Payment, IncomingWebhookEvent::PaymentIntentSuccess => Self::Payment, } } diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index e0a0204c024..8ad1a7419b3 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -17,7 +17,7 @@ where fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); - if val_str.len() < 15 && val_str.len() > 19 { + if val_str.len() < 15 || val_str.len() > 19 { return WithType::fmt(val, f); } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 86847a4469e..57e36436166 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -935,6 +935,7 @@ impl api::IncomingWebhook for Stripe { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(match details.event_type.as_str() { + "payment_intent.payment_failed" => api::IncomingWebhookEvent::PaymentIntentFailure, "payment_intent.succeeded" => api::IncomingWebhookEvent::PaymentIntentSuccess, _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?, }) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 9adbaa6b468..eab26a8553d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -31,7 +31,7 @@ use crate::{ utils::{ self, crypto::{self, SignMessage}, - OptionExt, ValueExt, + OptionExt, }, }; @@ -658,8 +658,9 @@ pub async fn get_connector_default( .parse_value("CustomRoutingRulesVec") .change_context(errors::ConnectorError::RoutingRulesParsingError) .change_context(errors::ApiErrorResponse::InternalServerError)?; - let custom_routing_rules: api::CustomRoutingRules = vec_val[0] - .clone() + let custom_routing_rules: api::CustomRoutingRules = vec_val + .first() + .cloned() .parse_value("CustomRoutingRules") .change_context(errors::ConnectorError::RoutingRulesParsingError) .change_context(errors::ApiErrorResponse::InternalServerError)?;
feat
add payment failed webhook event (#305)
343465165be0a573ec78a99be93386102a2a6615
2025-01-16 15:50:18
Amisha Prabhat
refactor(redis_interface): make the redis command for using scripts to write into redis Generic (#6965)
false
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 3c7ffa16ada..56e9ab98104 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -849,20 +849,23 @@ impl super::RedisConnectionPool { } #[instrument(level = "DEBUG", skip(self))] - pub async fn incr_keys_using_script<V>( + pub async fn evaluate_redis_script<V, T>( &self, lua_script: &'static str, key: Vec<String>, values: V, - ) -> CustomResult<(), errors::RedisError> + ) -> CustomResult<T, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, + T: serde::de::DeserializeOwned + FromRedis, { - self.pool + let val: T = self + .pool .eval(lua_script, key, values) .await - .change_context(errors::RedisError::IncrementHashFieldFailed) + .change_context(errors::RedisError::IncrementHashFieldFailed)?; + Ok(val) } } @@ -955,11 +958,10 @@ mod tests { .await .expect("failed to create redis connection pool"); let lua_script = r#" - local results = {} for i = 1, #KEYS do - results[i] = redis.call("INCRBY", KEYS[i], ARGV[i]) + redis.call("INCRBY", KEYS[i], ARGV[i]) end - return results + return "#; let mut keys_and_values = HashMap::new(); for i in 0..10 { @@ -973,7 +975,45 @@ mod tests { .collect::<Vec<String>>(); // Act - let result = pool.incr_keys_using_script(lua_script, key, values).await; + let result = pool + .evaluate_redis_script::<_, ()>(lua_script, key, values) + .await; + + // Assert Setup + result.is_ok() + }) + }) + .await + .expect("Spawn block failure"); + + assert!(is_success); + } + #[tokio::test] + async fn test_getting_keys_using_scripts() { + let is_success = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let pool = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + let lua_script = r#" + local results = {} + for i = 1, #KEYS do + results[i] = redis.call("GET", KEYS[i]) + end + return results + "#; + let mut keys_and_values = HashMap::new(); + for i in 0..10 { + keys_and_values.insert(format!("key{}", i), i); + } + + let key = keys_and_values.keys().cloned().collect::<Vec<_>>(); + + // Act + let result = pool + .evaluate_redis_script::<_, String>(lua_script, key, 0) + .await; // Assert Setup result.is_ok()
refactor
make the redis command for using scripts to write into redis Generic (#6965)
623cf4c841847f109597ee50017d6cfc0b4d9982
2024-07-25 18:39:28
Abhishek Kanojia
feat(events): forward the tenant configuration as part of the kafka message (#5224)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 941a315aaee..9c57f431ee6 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -699,7 +699,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 1cf8699f695..a7bd116a322 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -293,7 +293,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } diff --git a/config/development.toml b/config/development.toml index 48aa82b07a2..88dff87fe86 100644 --- a/config/development.toml +++ b/config/development.toml @@ -698,7 +698,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 61fdf86e457..7c750dd770b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -526,7 +526,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 7755740e1df..8fb38b35d99 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -854,7 +854,7 @@ impl AnalyticsProvider { pub async fn from_conf( config: &AnalyticsConfig, - tenant: &dyn storage_impl::config::ClickHouseConfig, + tenant: &dyn storage_impl::config::TenantConfig, ) -> Self { match config { AnalyticsConfig::Sqlx { sqlx } => { diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 9ed03c6d2ce..ec43259ad2f 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -43,14 +43,12 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); - let req_state = state.get_req_state(); let server_wrap_util_res = metrics::request::record_request_time_metric( api::server_wrap_util( &flow, state.clone().into(), request.headers(), - req_state, request, payload, func, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 64969b7d51a..8ccc97c73f4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -176,9 +176,6 @@ impl storage_impl::config::TenantConfig for Tenant { fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } -} - -impl storage_impl::config::ClickHouseConfig for Tenant { fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } @@ -188,6 +185,7 @@ impl storage_impl::config::ClickHouseConfig for Tenant { pub struct GlobalTenant { pub schema: String, pub redis_key_prefix: String, + pub clickhouse_database: String, } impl storage_impl::config::TenantConfig for GlobalTenant { @@ -197,6 +195,9 @@ impl storage_impl::config::TenantConfig for GlobalTenant { fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } + fn get_clickhouse_database(&self) -> &str { + self.clickhouse_database.as_str() + } } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 55fb7096a3a..02b43444511 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -26,7 +26,7 @@ use scheduler::{ SchedulerInterface, }; use serde::Serialize; -use storage_impl::redis::kv_store::RedisConnInterface; +use storage_impl::{config::TenantConfig, redis::kv_store::RedisConnInterface}; use time::PrimitiveDateTime; use super::{ @@ -89,7 +89,13 @@ pub struct KafkaStore { } impl KafkaStore { - pub async fn new(store: Store, kafka_producer: KafkaProducer, tenant_id: TenantID) -> Self { + pub async fn new( + store: Store, + mut kafka_producer: KafkaProducer, + tenant_id: TenantID, + tenant_config: &dyn TenantConfig, + ) -> Self { + kafka_producer.set_tenancy(tenant_config); Self { kafka_producer, diesel_store: store, diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index b7ab4ebaa1e..e9a1a17638c 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -6,7 +6,7 @@ use hyperswitch_domain_models::errors::{StorageError, StorageResult}; use masking::ErasedMaskSerialize; use router_env::logger; use serde::{Deserialize, Serialize}; -use storage_impl::errors::ApplicationError; +use storage_impl::{config::TenantConfig, errors::ApplicationError}; use time::PrimitiveDateTime; use crate::{ @@ -90,6 +90,11 @@ impl EventsHandler { Self::Logs(logger) => logger.log_event(event), }; } + pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) { + if let Self::Kafka(kafka_producer) = self { + kafka_producer.set_tenancy(tenant_config); + } + } } impl MessagingInterface for EventsHandler { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0e1be147fbd..8d456bb8fd8 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -340,6 +340,7 @@ impl AppState { .expect("Failed to create store"), kafka_client.clone(), TenantID(tenant.get_schema().to_string()), + tenant, ) .await, ), @@ -373,22 +374,19 @@ impl AppState { .await } - pub fn get_req_state(&self) -> ReqState { - ReqState { - event_context: events::EventContext::new(self.event_handler.clone()), - } - } pub fn get_session_state<E, F>(self: Arc<Self>, tenant: &str, err: F) -> Result<SessionState, E> where F: FnOnce() -> E + Copy, { let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?; + let mut event_handler = self.event_handler.clone(); + event_handler.add_tenant(tenant_conf); Ok(SessionState { store: self.stores.get(tenant).ok_or_else(err)?.clone(), global_store: self.global_store.clone(), conf: Arc::clone(&self.conf), api_client: self.api_client.clone(), - event_handler: self.event_handler.clone(), + event_handler, #[cfg(feature = "olap")] pool: self.pools.get(tenant).ok_or_else(err)?.clone(), file_storage_client: self.file_storage_client.clone(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 517d8a4df7d..bee82d8935d 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -692,22 +692,13 @@ pub enum AuthFlow { #[allow(clippy::too_many_arguments)] #[instrument( - skip( - request, - payload, - state, - func, - api_auth, - request_state, - incoming_request_header - ), + skip(request, payload, state, func, api_auth, incoming_request_header), fields(merchant_id) )] pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, state: web::Data<AppState>, incoming_request_header: &HeaderMap, - mut request_state: ReqState, request: &'a HttpRequest, payload: T, func: F, @@ -729,12 +720,6 @@ where .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; - request_state.event_context.record_info(request_id); - request_state - .event_context - .record_info(("flow".to_string(), flow.to_string())); - // request_state.event_context.record_info(request.clone()); - let mut app_state = state.get_ref().clone(); let start_instant = Instant::now(); @@ -767,9 +752,6 @@ where } })?? }; - request_state - .event_context - .record_info(("tenant_id".to_string(), tenant_id.to_string())); // let tenant_id = "public".to_string(); let mut session_state = Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || { @@ -779,6 +761,16 @@ where .switch() })?; session_state.add_request_id(request_id); + let mut request_state = session_state.get_req_state(); + + request_state.event_context.record_info(request_id); + request_state + .event_context + .record_info(("flow".to_string(), flow.to_string())); + + request_state + .event_context + .record_info(("tenant_id".to_string(), tenant_id.to_string())); // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth @@ -904,7 +896,6 @@ where ApplicationResponse<Q>: Debug, E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context, { - let req_state = state.get_req_state(); let request_method = request.method().as_str(); let url_path = request.path(); @@ -939,7 +930,6 @@ where &flow, state.clone(), incoming_request_header, - req_state, request, payload, func, diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index baa78339d91..78e08c1c60b 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -9,6 +9,8 @@ use rdkafka::{ message::{Header, OwnedHeaders}, producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, }; +use serde_json::Value; +use storage_impl::config::TenantConfig; #[cfg(feature = "payouts")] pub mod payout; use diesel_models::fraud_check::FraudCheck; @@ -70,21 +72,24 @@ struct KafkaEvent<'a, T: KafkaMessage> { event: &'a T, sign_flag: i32, tenant_id: TenantID, + clickhouse_database: Option<String>, } impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { - fn new(event: &'a T, tenant_id: TenantID) -> Self { + fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: 1, tenant_id, + clickhouse_database, } } - fn old(event: &'a T, tenant_id: TenantID) -> Self { + fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: -1, tenant_id, + clickhouse_database, } } } @@ -263,6 +268,7 @@ pub struct KafkaProducer { payout_analytics_topic: String, consolidated_events_topic: String, authentication_analytics_topic: String, + ckh_database_name: Option<String>, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -285,6 +291,10 @@ pub enum KafkaError { #[allow(unused)] impl KafkaProducer { + pub fn set_tenancy(&mut self, tenant_config: &dyn TenantConfig) { + self.ckh_database_name = Some(tenant_config.get_clickhouse_database().to_string()); + } + pub async fn create(conf: &KafkaSettings) -> MQResult<Self> { Ok(Self { producer: Arc::new(RdKafkaProducer( @@ -307,6 +317,7 @@ impl KafkaProducer { payout_analytics_topic: conf.payout_analytics_topic.clone(), consolidated_events_topic: conf.consolidated_events_topic.clone(), authentication_analytics_topic: conf.authentication_analytics_topic.clone(), + ckh_database_name: None, }) } @@ -342,6 +353,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaFraudCheck::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative fraud check event {negative_event:?}") @@ -351,6 +363,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaFraudCheck::from_storage(attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive fraud check event {attempt:?}") @@ -375,6 +388,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {negative_event:?}") @@ -384,6 +398,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaPaymentAttempt::from_storage(attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?; @@ -402,6 +417,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(delete_old_attempt), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {delete_old_attempt:?}") @@ -418,6 +434,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaAuthentication::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative authentication event {negative_event:?}") @@ -427,6 +444,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaAuthentication::from_storage(authentication), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive authentication event {authentication:?}") @@ -451,6 +469,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {negative_event:?}") @@ -460,6 +479,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaPaymentIntent::from_storage(intent), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?; @@ -478,6 +498,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(delete_old_intent), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {delete_old_intent:?}") @@ -494,6 +515,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {negative_event:?}") @@ -503,6 +525,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaRefund::from_storage(refund), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?; @@ -521,6 +544,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(delete_old_refund), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {delete_old_refund:?}") @@ -537,6 +561,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::old( &KafkaDispute::from_storage(&negative_event), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative dispute event {negative_event:?}") @@ -546,6 +571,7 @@ impl KafkaProducer { self.log_event(&KafkaEvent::new( &KafkaDispute::from_storage(dispute), tenant_id.clone(), + self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?; @@ -564,13 +590,21 @@ impl KafkaProducer { tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_payout { - self.log_event(&KafkaEvent::old(&negative_event, tenant_id.clone())) - .attach_printable_lazy(|| { - format!("Failed to add negative payout event {negative_event:?}") - })?; + self.log_event(&KafkaEvent::old( + &negative_event, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative payout event {negative_event:?}") + })?; }; - self.log_event(&KafkaEvent::new(payout, tenant_id.clone())) - .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) + self.log_event(&KafkaEvent::new( + payout, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) } #[cfg(feature = "payouts")] @@ -579,10 +613,14 @@ impl KafkaProducer { delete_old_payout: &KafkaPayout<'_>, tenant_id: TenantID, ) -> MQResult<()> { - self.log_event(&KafkaEvent::old(delete_old_payout, tenant_id.clone())) - .attach_printable_lazy(|| { - format!("Failed to add negative payout event {delete_old_payout:?}") - }) + self.log_event(&KafkaEvent::old( + delete_old_payout, + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative payout event {delete_old_payout:?}") + }) } pub fn get_topic(&self, event: EventType) -> &str { @@ -631,7 +669,14 @@ impl MessagingInterface for KafkaProducer { let topic = self.get_topic(data.get_message_class()); let json_data = data .masked_serialize() - .and_then(|i| serde_json::to_vec(&i)) + .and_then(|mut value| { + if let Value::Object(ref mut map) = value { + if let Some(db_name) = self.ckh_database_name.clone() { + map.insert("clickhouse_database".to_string(), Value::String(db_name)); + } + } + serde_json::to_vec(&value) + }) .change_context(EventsError::SerializationError)?; let mut headers = OwnedHeaders::new(); for (k, v) in metadata.iter() { @@ -640,6 +685,10 @@ impl MessagingInterface for KafkaProducer { value: Some(v), }); } + headers = headers.insert(Header { + key: "clickhouse_database", + value: self.ckh_database_name.as_ref(), + }); self.producer .0 .send( diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs index bb006b6a9e5..ac68d1718a9 100644 --- a/crates/storage_impl/src/config.rs +++ b/crates/storage_impl/src/config.rs @@ -36,9 +36,6 @@ impl DbConnectionParams for Database { pub trait TenantConfig: Send + Sync { fn get_schema(&self) -> &str; fn get_redis_key_prefix(&self) -> &str; -} - -pub trait ClickHouseConfig: TenantConfig + Send + Sync { fn get_clickhouse_database(&self) -> &str; }
feat
forward the tenant configuration as part of the kafka message (#5224)
371ed5de04eac32e36cd963fe249b8d2c045222c
2024-09-24 13:49:28
DEEPANSHU BANSAL
refactor(connector): Move cashtocode,coinbase,cryptopay to crate hyperswitch_connectors (#5983)
false
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 48c50936d60..f057b7d4a33 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -1,5 +1,8 @@ pub mod bambora; pub mod bitpay; +pub mod cashtocode; +pub mod coinbase; +pub mod cryptopay; pub mod deutschebank; pub mod fiserv; pub mod fiservemea; @@ -18,8 +21,9 @@ pub mod volt; pub mod worldline; pub use self::{ - bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv, - fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, - nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, - thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, + bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase, + cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea, + fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, + novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, volt::Volt, worldline::Worldline, }; diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs similarity index 67% rename from crates/router/src/connector/cashtocode.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs index 2155b80dd81..c72b63aebc0 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -1,33 +1,41 @@ pub mod transformers; - use base64::Engine; +use common_enums::enums; use common_utils::{ - request::RequestContent, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use diesel_models::enums; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; -use transformers as cashtocode; - -use super::utils as connector_utils; -use crate::{ - configs::settings::{self}, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + api::ApplicationResponse, + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - storage, ErrorResponse, Response, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, }, - utils::{ByteSliceExt, BytesExt}, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface, Secret}; +use transformers as cashtocode; + +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Cashtocode { @@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {} impl api::RefundSync for Cashtocode {} fn get_b64_auth_cashtocode( - payment_method_type: &Option<storage::enums::PaymentMethodType>, + payment_method_type: &Option<enums::PaymentMethodType>, auth_type: &transformers::CashtocodeAuth, -) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { +) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { fn construct_basic_auth( username: Option<Secret<String>>, password: Option<Secret<String>>, - ) -> Result<request::Maskable<String>, errors::ConnectorError> { + ) -> Result<masking::Maskable<String>, errors::ConnectorError> { let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( @@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode( } let auth_header = match payment_method_type { - Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth( + Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth( auth_type.username_classic.to_owned(), auth_type.password_classic.to_owned(), ), - Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth( + Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth( auth_type.username_evoucher.to_owned(), auth_type.password_evoucher.to_owned(), ), @@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode( Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)]) } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cashtocode { // Not Implemented (R) } @@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cashtocode.base_url.as_ref() } @@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cashtocode -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string()) .into(), @@ -193,17 +184,15 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_owned() .into(), )]; @@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/merchant/paytokens", @@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cashtocode::CashtocodePaymentsResponse = res .response .parse_struct("Cashtocode PaymentsAuthorizeResponse") @@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode { // default implementation of build_request method will be executed fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::CashtocodePaymentsSyncResponse = res .response .parse_struct("CashtocodePaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Cashtocode".to_string(), @@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Payments Cancel".to_string(), connector: "Cashtocode".to_string(), @@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } #[async_trait::async_trait] -impl api::IncomingWebhook for Cashtocode { +impl webhooks::IncomingWebhook for Cashtocode { fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let base64_signature = - connector_utils::get_header_key_value("authorization", request.headers)?; + let base64_signature = utils::get_header_key_value("authorization", request.headers)?; let signature = base64_signature.as_bytes().to_owned(); Ok(signature) } async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, @@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook: transformers::CashtocodePaymentsSyncResponse = request .body @@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook: transformers::CashtocodeIncomingWebhook = request .body @@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_api_response( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> - { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { let status = "EXECUTED".to_string(); let obj: transformers::CashtocodePaymentsSyncResponse = request .body @@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode { .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; let response: serde_json::Value = serde_json::json!({ "status": status, "transactionId" : obj.transaction_id}); - Ok(services::api::ApplicationResponse::Json(response)) + Ok(ApplicationResponse::Json(response)) } } -impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::refunds::Execute, - types::RefundsData, - types::RefundsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Execute, RefundsData, RefundsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds".to_string(), connector: "Cashtocode".to_string(), @@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu } } -impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode { // default implementation of build_request method will be executed } diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs similarity index 81% rename from crates/router/src/connector/cashtocode/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index e6f4b9e57cf..49493127621 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -1,18 +1,24 @@ use std::collections::HashMap; +use common_enums::enums; pub use common_utils::request::Method; use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit, }; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::{PaymentsAuthorizeData, ResponseId}, + router_response_types::{PaymentsResponseData, RedirectForm}, + types::PaymentsAuthorizeRouterData, +}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - services, - types::{self, storage::enums}, + types::ResponseRouterData, + utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; #[derive(Default, Debug, Serialize)] @@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest { } fn get_mid( - connector_auth_type: &types::ConnectorAuthType, + connector_auth_type: &ConnectorAuthType, payment_method_type: Option<enums::PaymentMethodType>, currency: enums::Currency, ) -> Result<Secret<String>, errors::ConnectorError> { @@ -50,10 +56,10 @@ fn get_mid( } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { +impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit), + (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit), ) -> Result<Self, Self::Error> { let customer_id = item.get_customer_id()?; let url = item.request.get_router_return_url()?; @@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco item.request.currency, )?; match item.payment_method { - diesel_models::enums::PaymentMethod::Reward => Ok(Self { + enums::PaymentMethod::Reward => Ok(Self { amount, transaction_id: item.attempt_id.clone(), currency: item.request.currency, @@ -96,12 +102,12 @@ pub struct CashtocodeAuth { pub merchant_id_evoucher: Option<Secret<String>>, } -impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { +impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { + ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { let transformed_auths = auth_key_map .iter() .map(|(currency, identity_auth_key)| { @@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { } } -impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { +impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { + fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { let (auth_type, currency) = value; - if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { + if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { if let Some(identity_auth_key) = auth_key_map.get(currency) { let cashtocode_auth: Self = identity_auth_key .to_owned() @@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse { fn get_redirect_form_data( payment_method_type: &enums::PaymentMethodType, response_data: CashtocodePaymentsResponseData, -) -> CustomResult<services::RedirectForm, errors::ConnectorError> { +) -> CustomResult<RedirectForm, errors::ConnectorError> { match payment_method_type { - enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form { + enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form { //redirect form is manually constructed because the connector for this pm type expects query params in the url endpoint: response_data.pay_url.to_string(), method: Method::Post, form_fields: Default::default(), }), - enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from(( + enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from(( //here the pay url gets parsed, and query params are sent as formfields as the connector expects response_data.pay_url, Method::Get, @@ -220,27 +226,27 @@ fn get_redirect_form_data( impl<F> TryFrom< - types::ResponseRouterData< + ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, - > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { CashtocodePaymentsResponse::CashtoCodeError(error_data) => ( enums::AttemptStatus::Failure, - Err(types::ErrorResponse { + Err(ErrorResponse { code: error_data.error.to_string(), status_code: item.http_code, message: error_data.error_description, @@ -259,8 +265,8 @@ impl<F> let redirection_data = get_redirect_form_data(payment_method_type, response_data)?; ( enums::AttemptStatus::AuthenticationPending, - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), ), redirection_data: Some(redirection_data), @@ -283,29 +289,17 @@ impl<F> } } -impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction. - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id ), redirection_data: None, diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs similarity index 64% rename from crates/router/src/connector/coinbase.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs index 0c3c0be41db..7b149952ca8 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -2,31 +2,45 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; -use diesel_models::enums; +use common_enums::enums; +use common_utils::{ + crypto, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::ResultExt; -use transformers as coinbase; - -use self::coinbase::CoinbaseWebhookDetails; -use super::utils; -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundsRouterData, }, - utils::BytesExt, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::Mask; +use transformers as coinbase; + +use self::coinbase::CoinbaseWebhookDetails; +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Debug, Clone)] pub struct Coinbase; @@ -50,9 +64,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), @@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.coinbase.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Coinbase { // Not Implemented (R) } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Coinbase -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Coinbase { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string()) .into(), @@ -178,14 +175,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/charges", self.base_url(_connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("Coinbase 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 { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_id = _req .request @@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("coinbase 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 { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase { fn build_request( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Coinbase".to_string(), @@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Coinbase -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase { fn build_request( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refund".to_string(), connector: "Coinbase".to_string(), @@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase { // default implementation of build_request method will be executed } #[async_trait::async_trait] -impl api::IncomingWebhook for Coinbase { +impl webhooks::IncomingWebhook for Coinbase { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body @@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.event.event_type { coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } coinbase::WebhookEventType::Failed => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } coinbase::WebhookEventType::Pending => { - Ok(api::IncomingWebhookEvent::PaymentIntentProcessing) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing) } coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => { - Ok(api::IncomingWebhookEvent::EventNotSupported) + Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs similarity index 87% rename from crates/router/src/connector/coinbase/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs index 82a6add72ee..3633c366c4c 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs @@ -1,15 +1,24 @@ use std::collections::HashMap; -use common_utils::pii; +use common_enums::enums; +use common_utils::{pii, request::Method}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - pii::Secret, - services, - types::{self, api, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{ + self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData, + }, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] @@ -46,10 +55,10 @@ pub struct CoinbaseAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType { +impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type { + fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::HeaderKey { api_key } = _auth_type { Ok(Self { api_key: api_key.to_owned(), }) @@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse { data: CoinbasePaymentResponseData, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CoinbasePaymentsResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let form_fields = HashMap::new(); - let redirection_data = services::RedirectForm::Form { + let redirection_data = RedirectForm::Form { endpoint: item.response.data.hosted_url.to_string(), - method: services::Method::Get, + method: Method::Get, form_fields, }; let timeline = item @@ -138,10 +141,10 @@ impl<F, T> .last() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .clone(); - let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone()); + let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = timeline.status.clone(); let response_data = timeline.context.map_or( - Ok(types::PaymentsResponseData::TransactionResponse { + Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id.clone(), redirection_data: Some(redirection_data), mandate_reference: None, @@ -152,9 +155,9 @@ impl<F, T> charge_id: None, }), |context| { - Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ + Ok(PaymentsResponseData::TransactionUnresolvedResponse{ resource_id: connector_id, - reason: Some(api::enums::UnresolvedResponseReason { + reason: Some(api_models::enums::UnresolvedResponseReason { code: context.to_string(), message: "Please check the transaction in coinbase dashboard and resolve manually" .to_string(), @@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse {} -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + _item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), @@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + _item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs similarity index 69% rename from crates/router/src/connector/cryptopay.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 765a07646c6..dcd629f4336 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -4,35 +4,44 @@ use base64::Engine; use common_utils::{ crypto::{self, GenerateDigest, SignMessage}, date_time, + errors::CustomResult, ext_traits::ByteSliceExt, - request::RequestContent, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hex::encode; -use masking::PeekInterface; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface}; use transformers as cryptopay; use self::cryptopay::CryptopayWebhookDetails; -use super::utils; use crate::{ - configs::settings, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - transformers::ForeignTryFrom, - ErrorResponse, Response, - }, - utils::BytesExt, + constants::headers, + types::ResponseRouterData, + utils::{self, ForeignTryFrom}, }; #[derive(Clone)] @@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {} impl api::RefundSync for Cryptopay {} impl api::PaymentToken for Cryptopay {} -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cryptopay { // Not Implemented (R) } @@ -77,16 +82,13 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let method = self.get_http_method(); let payload = match method { - common_utils::request::Method::Get => String::default(), - common_utils::request::Method::Post - | common_utils::request::Method::Put - | common_utils::request::Method::Delete - | common_utils::request::Method::Patch => { + Method::Get => String::default(), + Method::Post | Method::Put | Method::Delete | Method::Patch => { let body = self .get_request_body(req, connectors)? .get_inner_value() @@ -121,7 +123,7 @@ where ) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to sign the message")?; - let authz = consts::BASE64_ENGINE.encode(authz); + let authz = common_utils::consts::BASE64_ENGINE.encode(authz); let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz); let headers = vec![ @@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cryptopay.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = cryptopay::CryptopayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay { } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cryptopay -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cryptopay { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string()) .into(), @@ -225,14 +213,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/api/invoices", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, @@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("Cryptopay PaymentsAuthorizeResponse") @@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P impl ConnectorValidation for Cryptopay { fn validate_psync_reference_id( &self, - _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _data: &PaymentsSyncData, _is_three_ds: bool, _status: common_enums::enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, @@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay { } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe self.common_get_content_type() } - fn get_http_method(&self) -> services::Method { - services::Method::Get + fn get_http_method(&self) -> Method { + Method::Get } fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let custom_id = req.connector_request_reference_id.clone(); Ok(format!( @@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("cryptopay PaymentsSyncResponse") @@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {} #[async_trait::async_trait] -impl api::IncomingWebhook for Cryptopay { +impl webhooks::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request @@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request .body @@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.data.status { cryptopay::CryptopayPaymentStatus::Completed => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } cryptopay::CryptopayPaymentStatus::Unresolved => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } cryptopay::CryptopayPaymentStatus::Cancelled => { - Ok(api::IncomingWebhookEvent::PaymentIntentFailure) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure) } - _ => Ok(api::IncomingWebhookEvent::EventNotSupported), + _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported), } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs similarity index 76% rename from crates/router/src/connector/cryptopay/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index cd22890ca52..03a585f76bd 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -1,17 +1,23 @@ +use common_enums::enums; use common_utils::{ pii, types::{MinorUnit, StringMajorUnit}, }; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData}, - consts, - core::errors, - services, - types::{self, domain, storage::enums, transformers::ForeignTryFrom}, + types::ResponseRouterData, + utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData}, }; #[derive(Debug, Serialize)] @@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let cryptopay_request = match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Crypto(ref cryptodata) => { + PaymentMethodData::Crypto(ref cryptodata) => { let pay_currency = cryptodata.get_pay_currency()?; Ok(Self { price_amount: item.amount.clone(), @@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> custom_id: item.router_data.connector_request_reference_id.clone(), }) } - domain::PaymentMethodData::Card(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::MandatePayment {} - | domain::PaymentMethodData::Reward {} - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("CryptoPay"), - )) - } + PaymentMethodData::Card(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::MandatePayment {} + | PaymentMethodData::Reward {} + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("CryptoPay"), + )), }?; Ok(cryptopay_request) } @@ -96,10 +100,10 @@ pub struct CryptopayAuthType { pub(super) api_secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType { +impl TryFrom<&ConnectorAuthType> for CryptopayAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { api_key: api_key.to_owned(), api_secret: key1.to_owned(), @@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse { impl<F, T> ForeignTryFrom<( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, - )> for types::RouterData<F, T, types::PaymentsResponseData> + )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, amount_captured_in_minor_units): ( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, ), ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.data.status.clone()); - let response = if is_payment_failure(status) { + let response = if utils::is_payment_failure(status) { let payment_response = &item.response.data; - Err(types::ErrorResponse { + Err(ErrorResponse { code: payment_response .name .clone() @@ -173,11 +177,9 @@ impl<F, T> .response .data .hosted_page_url - .map(|x| services::RedirectForm::from((x, services::Method::Get))); - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.data.id.clone(), - ), + .map(|x| RedirectForm::from((x, common_utils::request::Method::Get))); + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 1093ef4e6f0..953b6316ff8 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, - utils::{self, AddressDetailsData, RouterData as _}, + utils::{self, is_payment_failure, AddressDetailsData, RouterData as _}, }; const PASSWORD: &str = "password"; @@ -605,32 +605,3 @@ pub struct VoltErrorList { pub property: String, pub message: 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, - } -} diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index c5ca6512a34..4c27e11fc45 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -10,6 +10,8 @@ pub(crate) mod headers { pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; pub(crate) const TIMESTAMP: &str = "Timestamp"; pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; + pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; + pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index a667c5ddc3c..31052ab0df2 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token { default_imp_for_authorize_session_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax { default_imp_for_calculate_tax!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update { default_imp_for_session_update!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization { default_imp_for_incremental_authorization!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer { default_imp_for_create_customer!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response { default_imp_for_connector_redirect_response!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{ default_imp_for_pre_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{ default_imp_for_post_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve { default_imp_for_approve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject { default_imp_for_reject!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification { default_imp_for_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute { default_imp_for_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence { default_imp_for_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute { default_imp_for_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload { default_imp_for_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create { default_imp_for_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve { default_imp_for_payouts_retrieve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility { default_imp_for_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill { default_imp_for_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel { default_imp_for_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote { default_imp_for_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient { default_imp_for_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account { default_imp_for_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale { default_imp_for_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout { default_imp_for_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction { default_imp_for_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment { default_imp_for_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return { default_imp_for_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates { default_imp_for_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 3bb1abfef21..16e592688ac 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment { default_imp_for_new_connector_integration_payment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund { default_imp_for_new_connector_integration_refund!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token { default_imp_for_new_connector_integration_connector_access_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute { default_imp_for_new_connector_integration_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence { default_imp_for_new_connector_integration_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute { default_imp_for_new_connector_integration_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload { default_imp_for_new_connector_integration_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create { default_imp_for_new_connector_integration_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel { default_imp_for_new_connector_integration_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote { default_imp_for_new_connector_integration_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient { default_imp_for_new_connector_integration_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync { default_imp_for_new_connector_integration_payouts_sync!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale { default_imp_for_new_connector_integration_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout { default_imp_for_new_connector_integration_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction { default_imp_for_new_connector_integration_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return { default_imp_for_new_connector_integration_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { default_imp_for_new_connector_integration_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index b2979975e55..f96d715f5be 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount use base64::Engine; use common_enums::{ enums, - enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, + enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, }; use common_utils::{ consts::BASE64_ENGINE, @@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>( .change_context(errors::ConnectorError::AmountConversionFailed) } +pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool { + match status { + AttemptStatus::AuthenticationFailed + | AttemptStatus::AuthorizationFailed + | AttemptStatus::CaptureFailed + | AttemptStatus::VoidFailed + | AttemptStatus::Failure => true, + AttemptStatus::Started + | AttemptStatus::RouterDeclined + | AttemptStatus::AuthenticationPending + | AttemptStatus::AuthenticationSuccessful + | AttemptStatus::Authorized + | AttemptStatus::Charged + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::Voided + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::AutoRefunded + | AttemptStatus::PartialCharged + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::Unresolved + | AttemptStatus::Pending + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::DeviceDataCollectionPending => false, + } +} + // TODO: Make all traits as `pub(crate) trait` once all connectors are moved. pub trait RouterData { fn get_billing(&self) -> Result<&Address, Error>; @@ -1460,6 +1489,18 @@ fn get_header_field( ))? } +pub trait CryptoData { + fn get_pay_currency(&self) -> Result<String, Error>; +} + +impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData { + fn get_pay_currency(&self) -> Result<String, Error> { + self.pay_currency + .clone() + .ok_or_else(missing_field_err("crypto_data.pay_currency")) + } +} + #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index b505f8c8c52..116fc67320f 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -9,10 +9,7 @@ pub mod billwerk; pub mod bluesnap; pub mod boku; pub mod braintree; -pub mod cashtocode; pub mod checkout; -pub mod coinbase; -pub mod cryptopay; pub mod cybersource; pub mod datatrans; pub mod dlocal; @@ -62,12 +59,13 @@ pub mod zen; pub mod zsl; pub use hyperswitch_connectors::connectors::{ - bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank, - fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, - globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay, - nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax, - stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, - worldline, worldline::Worldline, + bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode, + coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank, + deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, + fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, + nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, + stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, + volt::Volt, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] @@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, - billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, - cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, + billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, 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 041b5bb7359..3ff93cf9bf0 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e364d662e24..f9a6b461a13 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -209,10 +209,7 @@ default_imp_for_complete_authorize!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!( connector::Bluesnap, connector::Braintree, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -376,10 +370,7 @@ default_imp_for_create_customer!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -630,9 +618,6 @@ default_imp_for_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -739,9 +724,6 @@ default_imp_for_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -825,10 +807,7 @@ default_imp_for_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -911,10 +890,7 @@ default_imp_for_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1946,11 +1892,8 @@ default_imp_for_approve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2035,11 +1978,8 @@ default_imp_for_reject!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3158,10 +3071,7 @@ default_imp_for_session_update!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal,
refactor
Move cashtocode,coinbase,cryptopay to crate hyperswitch_connectors (#5983)
d533c98b5107fb6876c11b183eb9bc382a77a2f1
2024-01-16 17:59:22
DEEPANSHU BANSAL
feat(connector): [BANKOFAMERICA] Implement 3DS flow for cards (#3343)
false
diff --git a/config/config.example.toml b/config/config.example.toml index e20f9c1b65d..d4e11964192 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,6 +351,7 @@ 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"} diff --git a/config/development.toml b/config/development.toml index 5732d5f0d1d..91269005a0f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -428,6 +428,7 @@ 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"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c6934a64671..450fe106a31 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -241,6 +241,7 @@ 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"} diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index aeb3dafcfa2..0d901b99078 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -12,6 +12,7 @@ use time::OffsetDateTime; use transformers as bankofamerica; use url::Url; +use super::utils::{PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{utils as connector_utils, utils::RefundsRequestData}, @@ -48,6 +49,8 @@ impl api::Refund for Bankofamerica {} impl api::RefundExecute for Bankofamerica {} impl api::RefundSync for Bankofamerica {} impl api::PaymentToken for Bankofamerica {} +impl api::PaymentsPreProcessing for Bankofamerica {} +impl api::PaymentsCompleteAuthorize for Bankofamerica {} impl Bankofamerica { pub fn generate_digest(&self, payload: &[u8]) -> String { @@ -299,6 +302,113 @@ impl } } +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + 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::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let redirect_response = req.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )), + Some(_) | None => Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )), + } + } + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPreProcessingRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaPreProcessingResponse = res + .response + .parse_struct("BankOfAmerica AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Bankofamerica { @@ -316,13 +426,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) - )) + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}risk/v1/authentication-setups", + self.base_url(connectors) + )) + } else { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } } fn get_request_body( @@ -336,9 +450,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - let connector_req = - bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + if req.is_three_ds() && req.request.is_card() { + let connector_req = + bankofamerica::BankOfAmericaAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } else { + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } } fn build_request( @@ -368,6 +488,130 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + if data.is_three_ds() && data.request.is_card() { + let response: bankofamerica::BankOfAmericaAuthSetupResponse = res + .response + .parse_struct("Bankofamerica AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } else { + let response: bankofamerica::BankOfAmericaPaymentsResponse = res + .response + .parse_struct("Bankofamerica PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn get_5xx_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaServerErrorResponse = res + .response + .parse_struct("BankOfAmericaServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } +} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + 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::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica PaymentResponse") diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 6abe1b634df..72e3de0bf77 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments; use base64::Engine; -use common_utils::pii; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -8,10 +9,12 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, - PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData, + PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -85,14 +88,17 @@ pub struct BankOfAmericaPaymentsRequest { order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { - capture: bool, + capture: Option<bool>, payment_solution: Option<String>, + commerce_indicator: String, } #[derive(Debug, Serialize)] @@ -102,6 +108,17 @@ pub struct MerchantDefinedInformation { value: String, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + directory_server_transaction_id: Option<String>, + specification_version: Option<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { @@ -287,6 +304,28 @@ impl } } +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to, + } + } +} + impl From<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -300,11 +339,40 @@ impl ), ) -> Self { Self { - capture: matches!( + capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None - ), + )), payment_solution: solution.map(String::from), + commerce_indicator: String::from("internet"), + } + } +} + +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + )> for ProcessingInformation +{ + fn from( + (item, solution, three_ds_data): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + ), + ) -> Self { + Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + payment_solution: solution.map(String::from), + commerce_indicator: three_ds_data + .indicator + .to_owned() + .unwrap_or(String::from("internet")), } } } @@ -319,6 +387,16 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +impl From<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { let hashmap: std::collections::BTreeMap<String, Value> = @@ -367,6 +445,83 @@ pub struct Avs { code_raw: String, } +impl + TryFrom<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + + let three_ds_info: BankOfAmericaThreeDSMetadata = item + .router_data + .request + .connector_meta + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_meta", + })? + .parse_value("BankOfAmericaThreeDSMetadata") + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; + + let processing_information = + ProcessingInformation::from((item, None, &three_ds_info.three_ds_data)); + + let consumer_authentication_information = Some(BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, + cavv: three_ds_info.three_ds_data.cavv, + ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, + xid: three_ds_info.three_ds_data.xid, + directory_server_transaction_id: three_ds_info + .three_ds_data + .directory_server_transaction_id, + specification_version: three_ds_info.three_ds_data.specification_version, + }); + + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, + merchant_defined_information, + }) + } +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -410,6 +565,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -455,6 +611,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -496,6 +653,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -552,6 +710,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> order_information, merchant_defined_information, client_reference_information, + consumer_authentication_information: None, }) } } @@ -608,6 +767,64 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthSetupRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> + for BankOfAmericaAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaPaymentStatus { @@ -669,6 +886,29 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { } } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationResponse { + access_token: String, + device_data_collection_url: String, + reference_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthSetupInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaAuthSetupResponse { + ClientAuthSetupInfo(ClientAuthSetupInfoResponse), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaPaymentsResponse { @@ -799,6 +1039,494 @@ fn get_payment_response( } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }), + BankOfAmericaAuthSetupResponse::ErrorInformation(error_response) => { + let error_reason = error_response + .error_information + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationRequest { + return_url: String, + reference_id: String, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthEnrollmentRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationRequest, + order_information: OrderInformationWithBill, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct BankOfAmericaRedirectionAuthResponse { + pub transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthValidateRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationValidateRequest, + order_information: OrderInformation, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingRequest { + AuthEnrollment(BankOfAmericaAuthEnrollmentRequest), + AuthValidate(BankOfAmericaAuthValidateRequest), +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>> + for BankOfAmericaPreProcessingRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + Ok(PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + })) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => { + let reference_id = param + .clone() + .peek() + .split_once('=') + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .1 + .to_string(); + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to, + }; + Ok(Self::AuthEnrollment(BankOfAmericaAuthEnrollmentRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationRequest { + return_url: item.router_data.request.get_complete_authorize_url()?, + reference_id, + }, + order_information, + })) + } + Some(_) | None => { + let redirect_payload: BankOfAmericaRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("BankOfAmericaRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self::AuthValidate(BankOfAmericaAuthValidateRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + })) + } + } + } +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BankOfAmericaAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + specification_version: Option<String>, + directory_server_transaction_id: Option<String>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct BankOfAmericaThreeDSMetadata { + three_ds_data: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { + access_token: Option<String>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationEnrollmentResponse, + status: BankOfAmericaAuthEnrollmentStatus, + error_information: Option<BankOfAmericaErrorInformation>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + +impl From<BankOfAmericaAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: BankOfAmericaAuthEnrollmentStatus) -> Self { + match item { + BankOfAmericaAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + BankOfAmericaAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + BankOfAmericaAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(types::ErrorResponse::from(( + &info_response.error_information, + &risk_info, + item.http_code, + info_response.id.clone(), + ))); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(access_token), Some(step_up_url)) => { + Some(services::RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::json!({"three_ds_data":three_ds_data}), + ), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + BankOfAmericaPreProcessingResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } + } + } +} + impl<F> TryFrom< types::ResponseRouterData< diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 69159c10c8a..b300e97b44a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -874,6 +874,33 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } + + fn get_5xx_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::CybersourceServerErrorResponse = res + .response + .parse_struct("CybersourceServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(types::ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } } impl diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 21cdec92ccb..49a9bcf6664 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1489,7 +1489,8 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) - } else if connector.connector_name == router_types::Connector::Cybersource + } else if (connector.connector_name == router_types::Connector::Cybersource + || connector.connector_name == router_types::Connector::Bankofamerica) && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 6dd692f1525..c9f9d6d87f5 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -147,7 +147,6 @@ impl<const T: u8> default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, - connector::Bankofamerica, connector::Bitpay, connector::Boku, connector::Cashtocode, @@ -863,7 +862,6 @@ default_imp_for_pre_processing_steps!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, - connector::Bankofamerica, connector::Bitpay, connector::Bluesnap, connector::Boku,
feat
[BANKOFAMERICA] Implement 3DS flow for cards (#3343)
4eaa54e1386e59d02733787df0573d2f284dc684
2022-12-08 20:07:40
Sanchith Hegde
fix(connector-template): raise `ConnectorError` instead of `ValidateError` (#94)
false
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 32affb14c60..f379e016d71 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -6,7 +6,7 @@ use crate::{core::errors,types::{self,storage::enums}}; pub struct {{project-name | downcase | pascal_case}}PaymentsRequest {} impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase | pascal_case}}PaymentsRequest { - type Error = error_stack::Report<errors::ValidateError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &types::PaymentsAuthorizeRouterData) -> Result<Self,Self::Error> { todo!() } @@ -17,7 +17,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase pub struct {{project-name | downcase | pascal_case}}AuthType {} impl TryFrom<&types::ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType { - type Error = error_stack::Report<errors::ValidateError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { todo!() }
fix
raise `ConnectorError` instead of `ValidateError` (#94)
e44c32dd80a72aef37674a5fcc630f5ea88e6343
2023-09-01 19:41:57
chikke srujan
refactor(connector): [Shift4] refactor connector authorize request struct (#1888)
false
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index dc675968a9f..23c91e48d8c 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -8,8 +8,8 @@ use url::Url; use crate::{ connector::utils::{ - to_connector_meta, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - RouterData, + self, to_connector_meta, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, RouterData, }, core::errors, pii, services, @@ -18,18 +18,33 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; +#[derive(Debug, Serialize)] +pub struct Shift4PaymentsRequest { + amount: String, + currency: enums::Currency, + captured: bool, + #[serde(flatten)] + payment_method: Shift4PaymentMethod, +} + #[derive(Debug, Serialize)] #[serde(untagged)] -pub enum Shift4PaymentsRequest { - Non3DSRequest(Box<Shift4Non3DSRequest>), - ThreeDSRequest(Box<Shift43DSRequest>), +pub enum Shift4PaymentMethod { + CardsNon3DSRequest(Box<CardsNon3DSRequest>), + BankRedirectRequest(Box<BankRedirectRequest>), + Cards3DSRequest(Box<Cards3DSRequest>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct Shift43DSRequest { - amount: String, - currency: String, +pub struct BankRedirectRequest { + payment_method: PaymentMethod, + flow: Flow, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Cards3DSRequest { #[serde(rename = "card[number]")] pub card_number: CardNumber, #[serde(rename = "card[expMonth]")] @@ -42,20 +57,15 @@ pub struct Shift43DSRequest { #[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct Shift4Non3DSRequest { - amount: String, - card: Option<CardPayment>, - currency: String, +pub struct CardsNon3DSRequest { + card: CardPayment, description: Option<String>, - payment_method: Option<PaymentMethod>, - captured: bool, - flow: Option<Flow>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Flow { - pub return_url: Option<String>, + pub return_url: String, } #[derive(Debug, Serialize)] @@ -71,7 +81,7 @@ pub enum PaymentMethodType { pub struct PaymentMethod { #[serde(rename = "type")] method_type: PaymentMethodType, - billing: Option<Billing>, + billing: Billing, } #[derive(Debug, Serialize)] @@ -117,106 +127,283 @@ impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::Payme fn try_from( item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - match &item.request.payment_method_data { - api::PaymentMethodData::Card(ccard) => get_card_payment_request(item, ccard), - api::PaymentMethodData::BankRedirect(redirect_data) => { - get_bank_redirect_request(item, redirect_data) + let submit_for_settlement = item.request.is_auto_capture()?; + let amount = item.request.amount.to_string(); + let currency = item.request.currency; + let payment_method = Shift4PaymentMethod::try_from(item)?; + Ok(Self { + amount, + currency, + captured: submit_for_settlement, + payment_method, + }) + } +} + +impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>> + for Shift4PaymentMethod +{ + type Error = Error; + fn try_from( + item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + payments::PaymentMethodData::Card(ref ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::BankRedirect(ref redirect) => { + Self::try_from((item, redirect)) + } + payments::PaymentMethodData::Wallet(ref wallet_data) => Self::try_from(wallet_data), + payments::PaymentMethodData::BankTransfer(ref bank_transfer_data) => { + Self::try_from(bank_transfer_data.as_ref()) } - _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), + payments::PaymentMethodData::Voucher(ref voucher_data) => Self::try_from(voucher_data), + payments::PaymentMethodData::GiftCard(ref giftcard_data) => { + Self::try_from(giftcard_data.as_ref()) + } + payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()), } } } -impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>> - for Shift4PaymentsRequest -{ +impl TryFrom<&api_models::payments::WalletData> for Shift4PaymentMethod { + type Error = Error; + fn try_from(wallet_data: &api_models::payments::WalletData) -> Result<Self, Self::Error> { + match wallet_data { + payments::WalletData::AliPayRedirect(_) + | payments::WalletData::ApplePay(_) + | payments::WalletData::WeChatPayRedirect(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) + } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePay(_) + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()), + } + } +} + +impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { type Error = Error; fn try_from( - item: &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>, + bank_transfer_data: &api_models::payments::BankTransferData, ) -> Result<Self, Self::Error> { - match &item.request.payment_method_data { - Some(api::PaymentMethodData::Card(_)) => { - let card_token: Shift4CardToken = - to_connector_meta(item.request.connector_meta.clone())?; - Ok(Self::Non3DSRequest(Box::new(Shift4Non3DSRequest { - amount: item.request.amount.to_string(), - card: Some(CardPayment::CardToken(card_token.id)), - currency: item.request.currency.to_string(), - description: item.description.clone(), - captured: item.request.is_auto_capture()?, - payment_method: None, - flow: None, - }))) + match bank_transfer_data { + payments::BankTransferData::MultibancoBankTransfer { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) + } + payments::BankTransferData::AchBankTransfer { .. } + | payments::BankTransferData::SepaBankTransfer { .. } + | payments::BankTransferData::BacsBankTransfer { .. } + | payments::BankTransferData::PermataBankTransfer { .. } + | payments::BankTransferData::BcaBankTransfer { .. } + | payments::BankTransferData::BniVaBankTransfer { .. } + | payments::BankTransferData::BriVaBankTransfer { .. } + | payments::BankTransferData::CimbVaBankTransfer { .. } + | payments::BankTransferData::DanamonVaBankTransfer { .. } + | payments::BankTransferData::MandiriVaBankTransfer { .. } + | payments::BankTransferData::Pix {} + | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()), + } + } +} + +impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod { + type Error = Error; + fn try_from(voucher_data: &api_models::payments::VoucherData) -> Result<Self, Self::Error> { + match voucher_data { + payments::VoucherData::Boleto(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()), + payments::VoucherData::Efecty + | payments::VoucherData::PagoEfectivo + | payments::VoucherData::RedCompra + | payments::VoucherData::RedPagos + | payments::VoucherData::Alfamart(_) + | payments::VoucherData::Indomaret(_) + | payments::VoucherData::Oxxo + | payments::VoucherData::SevenEleven(_) + | payments::VoucherData::Lawson(_) + | payments::VoucherData::MiniStop(_) + | payments::VoucherData::FamilyMart(_) + | payments::VoucherData::Seicomart(_) + | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()), + } + } +} + +impl TryFrom<&api_models::payments::GiftCardData> for Shift4PaymentMethod { + type Error = Error; + fn try_from(gift_card_data: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> { + match gift_card_data { + payments::GiftCardData::Givex(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", } - _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), + .into()), + payments::GiftCardData::PaySafeCard {} => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()), } } } -fn get_card_payment_request<T>( - item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, - card: &api_models::payments::Card, -) -> Result<Shift4PaymentsRequest, Error> { - let submit_for_settlement = item.request.is_auto_capture()?; - let card = Card { - number: card.card_number.clone(), - exp_month: card.card_exp_month.clone(), - exp_year: card.card_exp_year.clone(), - cardholder_name: card.card_holder_name.clone(), - }; - if item.is_three_ds() { - Ok(Shift4PaymentsRequest::ThreeDSRequest(Box::new( - Shift43DSRequest { - amount: item.request.amount.to_string(), - currency: item.request.currency.to_string(), - card_number: card.number, - card_exp_month: card.exp_month, - card_exp_year: card.exp_year, +impl<T> + TryFrom<( + &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + &api_models::payments::Card, + )> for Shift4PaymentMethod +{ + type Error = Error; + fn try_from( + (item, card): ( + &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + &api_models::payments::Card, + ), + ) -> Result<Self, Self::Error> { + let card_object = Card { + number: card.card_number.clone(), + exp_month: card.card_exp_month.clone(), + exp_year: card.card_exp_year.clone(), + cardholder_name: card.card_holder_name.clone(), + }; + if item.is_three_ds() { + Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest { + card_number: card_object.number, + card_exp_month: card_object.exp_month, + card_exp_year: card_object.exp_year, return_url: item .request .complete_authorize_url .clone() .ok_or_else(|| errors::ConnectorError::RequestEncodingFailed)?, - }, - ))) - } else { - Ok(Shift4PaymentsRequest::Non3DSRequest(Box::new( - Shift4Non3DSRequest { - amount: item.request.amount.to_string(), - card: Some(CardPayment::RawCard(Box::new(card))), - currency: item.request.currency.to_string(), + }))) + } else { + Ok(Self::CardsNon3DSRequest(Box::new(CardsNon3DSRequest { + card: CardPayment::RawCard(Box::new(card_object)), description: item.description.clone(), - captured: submit_for_settlement, - payment_method: None, - flow: None, - }, - ))) + }))) + } } } -fn get_bank_redirect_request<T>( - item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, - redirect_data: &payments::BankRedirectData, -) -> Result<Shift4PaymentsRequest, Error> { - let submit_for_settlement = item.request.is_auto_capture()?; - let method_type = PaymentMethodType::try_from(redirect_data)?; - let billing = get_billing(item)?; - let payment_method = Some(PaymentMethod { - method_type, - billing, - }); - let flow = get_flow(item); - Ok(Shift4PaymentsRequest::Non3DSRequest(Box::new( - Shift4Non3DSRequest { - amount: item.request.amount.to_string(), - card: None, - currency: item.request.currency.to_string(), - description: item.description.clone(), - captured: submit_for_settlement, +impl<T> + TryFrom<( + &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + &payments::BankRedirectData, + )> for Shift4PaymentMethod +{ + type Error = Error; + fn try_from( + (item, redirect_data): ( + &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + &payments::BankRedirectData, + ), + ) -> Result<Self, Self::Error> { + let flow = Flow::try_from(&item.request.router_return_url)?; + let method_type = PaymentMethodType::try_from(redirect_data)?; + let billing = Billing::try_from(item)?; + let payment_method = PaymentMethod { + method_type, + billing, + }; + Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest { payment_method, - flow: Some(flow), - }, - ))) + flow, + }))) + } +} + +impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>> + for Shift4PaymentsRequest +{ + type Error = Error; + fn try_from( + item: &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + match &item.request.payment_method_data { + Some(api::PaymentMethodData::Card(_)) => { + let card_token: Shift4CardToken = + to_connector_meta(item.request.connector_meta.clone())?; + Ok(Self { + amount: item.request.amount.to_string(), + currency: item.request.currency, + payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new( + CardsNon3DSRequest { + card: CardPayment::CardToken(card_token.id), + description: item.description.clone(), + }, + )), + captured: item.request.is_auto_capture()?, + }) + } + Some(payments::PaymentMethodData::Wallet(_)) + | Some(payments::PaymentMethodData::GiftCard(_)) + | Some(payments::PaymentMethodData::CardRedirect(_)) + | Some(payments::PaymentMethodData::PayLater(_)) + | Some(payments::PaymentMethodData::BankDebit(_)) + | Some(payments::PaymentMethodData::BankRedirect(_)) + | Some(payments::PaymentMethodData::BankTransfer(_)) + | Some(payments::PaymentMethodData::Crypto(_)) + | Some(payments::PaymentMethodData::MandatePayment) + | Some(payments::PaymentMethodData::Voucher(_)) + | Some(payments::PaymentMethodData::Reward) + | Some(payments::PaymentMethodData::Upi(_)) + | None => Err(errors::ConnectorError::NotSupported { + message: "Flow".to_string(), + connector: "Shift4", + } + .into()), + } + } } impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { @@ -227,35 +414,66 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay), payments::BankRedirectData::Ideal { .. } => Ok(Self::Ideal), payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort), - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + payments::BankRedirectData::BancontactCard { .. } + | payments::BankRedirectData::Blik { .. } + | payments::BankRedirectData::Trustly { .. } + | payments::BankRedirectData::Przelewy24 { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) + } + payments::BankRedirectData::Bizum {} + | payments::BankRedirectData::Interac { .. } + | payments::BankRedirectData::OnlineBankingCzechRepublic { .. } + | payments::BankRedirectData::OnlineBankingFinland { .. } + | payments::BankRedirectData::OnlineBankingPoland { .. } + | payments::BankRedirectData::OnlineBankingSlovakia { .. } + | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::OnlineBankingFpx { .. } + | payments::BankRedirectData::OnlineBankingThailand { .. } => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()) + } } } } -fn get_flow<T>( - item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, -) -> Flow { - Flow { - return_url: item.request.router_return_url.clone(), +impl TryFrom<&Option<String>> for Flow { + type Error = Error; + fn try_from(router_return_url: &Option<String>) -> Result<Self, Self::Error> { + Ok(Self { + return_url: router_return_url + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?, + }) } } -fn get_billing<T>( - item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, -) -> Result<Option<Billing>, Error> { - let billing_address = item - .address - .billing - .as_ref() - .and_then(|billing| billing.address.as_ref()); - let address = get_address_details(billing_address); - Ok(Some(Billing { - name: billing_address.map(|billing| { - Secret::new(format!("{:?} {:?}", billing.first_name, billing.last_name)) - }), - email: item.request.email.clone(), - address, - })) +impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>> + for Billing +{ + type Error = Error; + fn try_from( + item: &types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let billing_address = item + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()); + let address = get_address_details(billing_address); + Ok(Self { + name: billing_address.map(|billing| { + Secret::new(format!("{:?} {:?}", billing.first_name, billing.last_name)) + }), + email: item.request.email.clone(), + address, + }) + } } fn get_address_details(address_details: Option<&payments::AddressDetails>) -> Option<Address> { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 04fc518ba1b..90ac405e5c8 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -74,6 +74,7 @@ pub trait RouterData { #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; } +pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String { format!("Selected payment method through {}", connector)
refactor
[Shift4] refactor connector authorize request struct (#1888)
7b1c65b60d3874262867f77c8c28ebfa410b89a3
2024-02-14 15:12:01
Chethan Rao
refactor: incorporate `hyperswitch_interface` into drainer (#3629)
false
diff --git a/Cargo.lock b/Cargo.lock index dc732bdfd69..2c9293c1701 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2342,6 +2342,7 @@ dependencies = [ "diesel_models", "error-stack", "external_services", + "hyperswitch_interfaces", "masking", "mime", "once_cell", diff --git a/config/deployments/drainer.toml b/config/deployments/drainer.toml index 42c89cbfd58..f8bf2826768 100644 --- a/config/deployments/drainer.toml +++ b/config/deployments/drainer.toml @@ -5,7 +5,17 @@ num_partitions = 64 shutdown_interval = 1000 stream_name = "drainer_stream" -[kms] +[secrets_management] +secrets_manager = "aws_kms" + +[secrets_management.aws_kms] +key_id = "kms_key_id" +region = "kms_region" + +[encryption_management] +encryption_manager = "aws_kms" + +[encryption_management.aws_kms] key_id = "kms_key_id" region = "kms_region" diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index cde7185affa..725c6a123f1 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -35,6 +35,7 @@ async-trait = "0.1.74" common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } external_services = { version = "0.1.0", path = "../external_services" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index e01b72150c5..c539e9a734c 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -1,23 +1,13 @@ use bb8::PooledConnection; use diesel::PgConnection; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::{ - core::{HashiCorpVault, Kv2}, - decrypt::VaultFetch, -}; -#[cfg(not(feature = "aws_kms"))] use masking::PeekInterface; -use crate::settings::Database; +use crate::{settings::Database, Settings}; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; #[allow(clippy::expect_used)] -pub async fn redis_connection( - conf: &crate::settings::Settings, -) -> redis_interface::RedisConnectionPool { +pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await .expect("Failed to create Redis connection Pool") @@ -28,31 +18,14 @@ pub async fn redis_connection( /// /// Will panic if could not create a db pool #[allow(clippy::expect_used)] -pub async fn diesel_make_pg_pool( - database: &Database, - _test_transaction: bool, - #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static HashiCorpVault, -) -> PgPool { - let password = database.password.clone(); - #[cfg(feature = "hashicorp-vault")] - let password = password - .fetch_inner::<Kv2>(hashicorp_client) - .await - .expect("Failed while fetching db password"); - - #[cfg(feature = "aws_kms")] - let password = password - .decrypt_inner(aws_kms_client) - .await - .expect("Failed to decrypt password"); - - #[cfg(not(feature = "aws_kms"))] - let password = &password.peek(); - +pub async fn diesel_make_pg_pool(database: &Database, _test_transaction: bool) -> PgPool { let database_url = format!( "postgres://{}:{}@{}:{}/{}", - database.username, password, database.host, database.port, database.dbname + database.username, + database.password.peek(), + database.host, + database.port, + database.dbname ); let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); let pool = bb8::Pool::builder() diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 33b4a1395a8..443cb5b6f3f 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -11,7 +11,7 @@ use crate::{ connection::{pg_connection, redis_connection}, errors::HealthCheckError, services::{self, Store}, - settings::Settings, + Settings, }; pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0"; diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 909ae065e26..0ed6183faef 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -11,19 +11,20 @@ mod stream; mod types; mod utils; use std::sync::Arc; +mod secrets_transformers; use actix_web::dev::Server; 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 tokio::sync::mpsc; +pub(crate) type Settings = crate::settings::Settings<RawSecret>; + use crate::{ - connection::pg_connection, - services::Store, - settings::{DrainerSettings, Settings}, - types::StreamData, + connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData, }; pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::DrainerResult<()> { diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 943a66f6791..377fdcd1569 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -15,7 +15,9 @@ async fn main() -> DrainerResult<()> { conf.validate() .expect("Failed to validate drainer configuration"); - let store = services::Store::new(&conf, false).await; + let state = settings::AppState::new(conf.clone()).await; + + let store = services::Store::new(&state.conf, false).await; let store = std::sync::Arc::new(store); #[cfg(feature = "vergen")] @@ -28,7 +30,7 @@ async fn main() -> DrainerResult<()> { ); #[allow(clippy::expect_used)] - let web_server = Box::pin(start_web_server(conf.clone(), store.clone())) + let web_server = Box::pin(start_web_server(state.conf.as_ref().clone(), store.clone())) .await .expect("Failed to create the server"); diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rs new file mode 100644 index 00000000000..c0447725a79 --- /dev/null +++ b/crates/drainer/src/secrets_transformers.rs @@ -0,0 +1,50 @@ +use common_utils::errors::CustomResult; +use hyperswitch_interfaces::secrets_interface::{ + secret_handler::SecretsHandler, + secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, + SecretManagementInterface, SecretsManagementError, +}; + +use crate::settings::{Database, Settings}; + +#[async_trait::async_trait] +impl SecretsHandler for Database { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: Box<dyn SecretManagementInterface>, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let secured_db_config = value.get_inner(); + let raw_db_password = secret_management_client + .get_secret(secured_db_config.password.clone()) + .await?; + + Ok(value.transition_state(|db| Self { + password: raw_db_password, + ..db + })) + } +} + +/// # Panics +/// +/// Will panic even if fetching raw secret fails for at least one config value +#[allow(clippy::unwrap_used)] +pub async fn fetch_raw_secrets( + conf: Settings<SecuredSecret>, + secret_management_client: Box<dyn SecretManagementInterface>, +) -> Settings<RawSecret> { + #[allow(clippy::expect_used)] + let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client) + .await + .expect("Failed to decrypt database password"); + + Settings { + server: conf.server, + master_database: database, + redis: conf.redis, + log: conf.log, + drainer: conf.drainer, + encryption_management: conf.encryption_management, + secrets_management: conf.secrets_management, + } +} diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 3918c756c10..9e0165548a0 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -28,20 +28,10 @@ impl Store { /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. /// - pub async fn new(config: &crate::settings::Settings, test_transaction: bool) -> Self { + pub async fn new(config: &crate::Settings, test_transaction: bool) -> Self { Self { - master_pool: diesel_make_pg_pool( - &config.master_database, - test_transaction, - #[cfg(feature = "aws_kms")] - external_services::aws_kms::core::get_aws_kms_client(&config.kms).await, - #[cfg(feature = "hashicorp-vault")] - #[allow(clippy::expect_used)] - external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) - .await - .expect("Failed while getting hashicorp client"), - ) - .await, + master_pool: diesel_make_pg_pool(config.master_database.get_inner(), test_transaction) + .await, redis_conn: Arc::new(crate::connection::redis_connection(config).await), config: StoreConfig { drainer_stream_name: config.drainer.stream_name.clone(), diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index de5af654540..ec24c472af2 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -1,22 +1,23 @@ -use std::path::PathBuf; +use std::{path::PathBuf, sync::Arc}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault; +use external_services::managers::{ + encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, +}; +use hyperswitch_interfaces::{ + encryption_interface::EncryptionManagementInterface, + secrets_interface::secret_state::{ + RawSecret, SecretState, SecretStateContainer, SecuredSecret, + }, +}; +use masking::Secret; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; use serde::Deserialize; -use crate::errors; - -#[cfg(feature = "aws_kms")] -pub type Password = aws_kms::core::AwsKmsValue; -#[cfg(not(feature = "aws_kms"))] -pub type Password = masking::Secret<String>; +use crate::{errors, secrets_transformers}; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] @@ -27,25 +28,58 @@ pub struct CmdLineConf { pub config_path: Option<PathBuf>, } +#[derive(Clone)] +pub struct AppState { + pub conf: Arc<Settings<RawSecret>>, + pub encryption_client: Box<dyn EncryptionManagementInterface>, +} + +impl AppState { + /// # Panics + /// + /// Panics if secret or encryption management client cannot be initiated + pub async fn new(conf: Settings<SecuredSecret>) -> Self { + #[allow(clippy::expect_used)] + let secret_management_client = conf + .secrets_management + .get_secret_management_client() + .await + .expect("Failed to create secret management client"); + + let raw_conf = + secrets_transformers::fetch_raw_secrets(conf, secret_management_client).await; + + #[allow(clippy::expect_used)] + let encryption_client = raw_conf + .encryption_management + .get_encryption_management_client() + .await + .expect("Failed to create encryption management client"); + + Self { + conf: Arc::new(raw_conf), + encryption_client, + } + } +} + #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] -pub struct Settings { +pub struct Settings<S: SecretState> { pub server: Server, - pub master_database: Database, + pub master_database: SecretStateContainer<Database, S>, pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, - #[cfg(feature = "aws_kms")] - pub kms: aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, + pub encryption_management: EncryptionManagementConfig, + pub secrets_management: SecretsManagementConfig, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, - pub password: Password, + pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, @@ -85,7 +119,7 @@ impl Default for Database { fn default() -> Self { Self { username: String::new(), - password: Password::default(), + password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), @@ -157,7 +191,7 @@ impl DrainerSettings { } } -impl Settings { +impl Settings<SecuredSecret> { pub fn new() -> Result<Self, errors::DrainerError> { Self::with_config_path(None) } @@ -199,12 +233,25 @@ impl Settings { pub fn validate(&self) -> Result<(), errors::DrainerError> { self.server.validate()?; - self.master_database.validate()?; + self.master_database.get_inner().validate()?; self.redis.validate().map_err(|error| { println!("{error}"); errors::DrainerError::ConfigParsingError("invalid Redis configuration".into()) })?; self.drainer.validate()?; + self.secrets_management.validate().map_err(|error| { + println!("{error}"); + errors::DrainerError::ConfigParsingError( + "invalid secrets management configuration".into(), + ) + })?; + + self.encryption_management.validate().map_err(|error| { + println!("{error}"); + errors::DrainerError::ConfigParsingError( + "invalid encryption management configuration".into(), + ) + })?; Ok(()) } diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs index 6d3f75500af..d1da6a8c8b6 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs @@ -8,12 +8,12 @@ use serde::{Deserialize, Deserializer}; pub trait SecretState {} /// Decrypted state -#[derive(Debug, Clone, Deserialize)] -pub enum RawSecret {} +#[derive(Debug, Clone, Deserialize, Default)] +pub struct RawSecret {} /// Encrypted state -#[derive(Debug, Clone, Deserialize)] -pub enum SecuredSecret {} +#[derive(Debug, Clone, Deserialize, Default)] +pub struct SecuredSecret {} impl SecretState for RawSecret {} impl SecretState for SecuredSecret {}
refactor
incorporate `hyperswitch_interface` into drainer (#3629)
10371af561ecc7536bb1db191af90a3cac2ab515
2025-03-19 05:59:18
github-actions
chore(version): 2025.03.19.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 77e5e47d3ab..189e6c628c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ All notable changes to HyperSwitch will be documented here. +- - - + +## 2025.03.19.0 + +### Features + +- **analytics:** Add issuer as filter for authentication analytics ([#7535](https://github.com/juspay/hyperswitch/pull/7535)) ([`a87471c`](https://github.com/juspay/hyperswitch/commit/a87471c45dee50e7b9c9674aa8c9bb668c892917)) +- **connector:** + - [Chargebee] Add record back support for chargebee ([#7505](https://github.com/juspay/hyperswitch/pull/7505)) ([`e77bb71`](https://github.com/juspay/hyperswitch/commit/e77bb71c6c8c13a343d877481fe2e75cdd98e18c)) + - [Nexixpay] add setup mandate flow ([#7532](https://github.com/juspay/hyperswitch/pull/7532)) ([`f6633a7`](https://github.com/juspay/hyperswitch/commit/f6633a72d5f826804c6a24317f8e5c836b0bc95a)) + +### Bug Fixes + +- **connector:** + - [BRAINTREE] Added fix for Braintree Creds Identifier ([#7501](https://github.com/juspay/hyperswitch/pull/7501)) ([`a161f24`](https://github.com/juspay/hyperswitch/commit/a161f24773abd38435b40b41540d1cab1a722b7c)) + - Handle Sequential Automatic case in MIT payments ([#6833](https://github.com/juspay/hyperswitch/pull/6833)) ([`e4c7ab8`](https://github.com/juspay/hyperswitch/commit/e4c7ab8e683d969092910b3fcc046c2e65e18df9)) + +### Refactors + +- **core:** Revert "filter default routing config response based on connector type" ([#7556](https://github.com/juspay/hyperswitch/pull/7556)) ([`66e507e`](https://github.com/juspay/hyperswitch/commit/66e507e017fa7416f33aeae5f1ee60fd65d1d8b0)) + +**Full Changelog:** [`2025.03.18.0...2025.03.19.0`](https://github.com/juspay/hyperswitch/compare/2025.03.18.0...2025.03.19.0) + + - - - ## 2025.03.18.0
chore
2025.03.19.0
8497c55283d548c04b3a01560b06d9594e7d634c
2023-06-09 15:02:17
Narayan Bhat
fix: certificate decode failed when creating the session token for applepay (#1385)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c53acb6d853..7df67b13a54 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1711,6 +1711,12 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ConnectorMetadata { + pub apple_pay: Option<ApplePayMetadata>, + pub google_pay: Option<GpayMetaData>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { #[serde(rename = "apple_pay")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 72f2e9eaa92..c36ba7c734d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -380,6 +380,36 @@ fn get_business_details_wrapper( } } +fn validate_certificate_in_mca_metadata( + connector_metadata: Secret<serde_json::Value>, +) -> RouterResult<()> { + let parsed_connector_metadata = connector_metadata + .parse_value::<api_models::payments::ConnectorMetadata>("ApplepaySessionTokenData") + .change_context(errors::ParsingError::StructParseFailure("Metadata")) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "metadata".to_string(), + expected_format: "connector metadata".to_string(), + })?; + + parsed_connector_metadata + .apple_pay + .map(|applepay_metadata| { + let api_models::payments::SessionTokenInfo { + certificate, + certificate_keys, + .. + } = applepay_metadata.session_token_data; + helpers::create_identity_from_certificate_and_key(certificate, certificate_keys) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "certificate/certificate key", + }) + .map(|_identity_result| ()) + }) + .transpose()?; + + Ok(()) +} + pub async fn create_payment_connector( store: &dyn StorageInterface, req: api::MerchantConnectorCreate, @@ -390,6 +420,11 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to get key from merchant key store")?; + req.metadata + .clone() + .map(validate_certificate_in_mca_metadata) + .transpose()?; + let merchant_account = store .find_merchant_account_by_merchant_id(merchant_id) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3147ef8026b..3723799e232 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; +use base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, fp_utils, generate_id, pii, @@ -46,6 +47,33 @@ use crate::{ }, }; +pub fn create_identity_from_certificate_and_key( + encoded_certificate: String, + encoded_certificate_key: String, +) -> Result<reqwest::Identity, error_stack::Report<errors::ApiClientError>> { + let decoded_certificate = consts::BASE64_ENGINE + .decode(encoded_certificate) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let decoded_certificate_key = consts::BASE64_ENGINE + .decode(encoded_certificate_key) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + let certificate_key = String::from_utf8(decoded_certificate_key) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + + reqwest::Identity::from_pkcs8_pem(certificate.as_bytes(), certificate_key.as_bytes()) + .into_report() + .change_context(errors::ApiClientError::CertificateDecodeFailed) +} + pub fn filter_mca_based_on_business_details( merchant_connector_accounts: Vec<domain::MerchantConnectorAccount>, payment_intent: Option<&storage_models::payment_intent::PaymentIntent>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 3d6ba2afcb3..d37f22f750a 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -1,11 +1,12 @@ -use base64::Engine; use error_stack::{IntoReport, ResultExt}; use once_cell::sync::OnceCell; use crate::{ configs::settings::{Locker, Proxy}, - consts, - core::errors::{self, CustomResult}, + core::{ + errors::{self, CustomResult}, + payments, + }, }; static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); @@ -74,30 +75,13 @@ pub(super) fn create_client( client_certificate_key: Option<String>, ) -> CustomResult<reqwest::Client, errors::ApiClientError> { match (client_certificate, client_certificate_key) { - (Some(encoded_cert), Some(encoded_cert_key)) => { + (Some(encoded_certificate), Some(encoded_certificate_key)) => { let client_builder = get_client_builder(proxy_config, should_bypass_proxy)?; - let decoded_cert = consts::BASE64_ENGINE - .decode(encoded_cert) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let decoded_cert_key = consts::BASE64_ENGINE - .decode(encoded_cert_key) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_cert) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let certificate_key = String::from_utf8(decoded_cert_key) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; - let identity = reqwest::Identity::from_pkcs8_pem( - certificate.as_bytes(), - certificate_key.as_bytes(), - ) - .into_report() - .change_context(errors::ApiClientError::CertificateDecodeFailed)?; + let identity = payments::helpers::create_identity_from_certificate_and_key( + encoded_certificate, + encoded_certificate_key, + )?; client_builder .identity(identity)
fix
certificate decode failed when creating the session token for applepay (#1385)
a16fc653cf1e3c79e7502eec261b050fab046335
2023-01-16 18:23:44
Arjun Karthik
feature(connector): add support for worldline connector (#374)
false
diff --git a/Cargo.lock b/Cargo.lock index 3812b1bb856..b14223062dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3015,6 +3015,7 @@ dependencies = [ "once_cell", "rand 0.8.5", "redis_interface", + "regex", "reqwest", "ring", "router_derive", diff --git a/config/Development.toml b/config/Development.toml index fa61e28810c..e0315b066fc 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -93,6 +93,9 @@ base_url = "https://secure.snd.payu.com/api/" [connectors.globalpay] base_url = "https://apis.sandbox.globalpay.com/ucp/" +[connectors.worldline] +base_url = "https://eu.sandbox.api-ingenico.com/" + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 83ead25c354..0c77ca85bff 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -509,6 +509,7 @@ pub enum Connector { Payu, Shift4, Stripe, + Worldline, Worldpay, } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 9c95e070ab0..45aeb8d377d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -53,6 +53,7 @@ nanoid = "0.4.0" num_cpus = "1.15.0" once_cell = "1.17.0" rand = "0.8.5" +regex = "1.7.1" reqwest = { version = "0.11.13", features = ["json", "native-tls", "gzip"] } ring = "0.16.20" serde = { version = "1.0.152", features = ["derive"] } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3aeb0fc0410..1f66cb22ff2 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -134,6 +134,7 @@ pub struct Connectors { pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, + pub worldline: ConnectorParams, pub worldpay: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 2b9ef18559f..4c218454d99 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -12,11 +12,12 @@ pub mod payu; pub mod shift4; pub mod stripe; pub mod utils; +pub mod worldline; pub mod worldpay; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, fiserv::Fiserv, globalpay::Globalpay, klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe, - worldpay::Worldpay, + worldline::Worldline, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs new file mode 100644 index 00000000000..50419ee2b9c --- /dev/null +++ b/crates/router/src/connector/worldline.rs @@ -0,0 +1,606 @@ +mod transformers; + +use std::fmt::Debug; + +use base64::Engine; +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use ring::hmac; +use time::{format_description, OffsetDateTime}; +use transformers as worldline; + +use crate::{ + configs::settings::Connectors, + consts, + core::errors::{self, CustomResult}, + headers, logger, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon}, + ErrorResponse, Response, + }, + utils::{self, BytesExt, OptionExt}, +}; + +#[derive(Debug, Clone)] +pub struct Worldline; + +impl Worldline { + pub fn generate_authorization_token( + &self, + auth: worldline::AuthType, + http_method: &services::Method, + content_type: &str, + date: &str, + endpoint: &str, + ) -> CustomResult<String, errors::ConnectorError> { + let signature_data: String = format!( + "{}\n{}\n{}\n/{}\n", + http_method, + content_type.trim(), + date.trim(), + endpoint.trim() + ); + let worldline::AuthType { + api_key, + api_secret, + .. + } = auth; + let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.as_bytes()); + let signed_data = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_data.as_bytes())); + + Ok(format!("GCS v1HMAC:{api_key}:{signed_data}")) + } + + pub fn get_current_date_time() -> CustomResult<String, errors::ConnectorError> { + let format = format_description::parse( + "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT", + ) + .into_report() + .change_context(errors::ConnectorError::InvalidDateFormat)?; + OffsetDateTime::now_utc() + .format(&format) + .into_report() + .change_context(errors::ConnectorError::InvalidDateFormat) + } +} + +impl ConnectorCommon for Worldline { + fn id(&self) -> &'static str { + "worldline" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.worldline.base_url.as_ref() + } + + fn build_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: worldline::ErrorResponse = res + .parse_struct("Worldline ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let error = response.errors.into_iter().next().unwrap_or_default(); + Ok(ErrorResponse { + code: error + .code + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: error + .message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + ..Default::default() + }) + } +} + +impl api::Payment for Worldline {} + +impl api::PreVerify for Worldline {} +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Worldline +{ +} + +impl api::PaymentVoid for Worldline {} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsVoidType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let http_method = services::Method::Post; + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::PaymentsAuthorizeType::get_content_type(self); + let signed_data: String = + self.generate_authorization_token(auth, &http_method, content_type, &date, &endpoint)?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + let payment_id: &str = req.request.connector_transaction_id.as_ref(); + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}/cancel" + )) + } + + fn build_request( + &self, + req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: worldline::PaymentResponse = res + .response + .parse_struct("PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(payments_cancel_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::PaymentSync for Worldline {} +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsSyncType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let signed_data: String = + self.generate_authorization_token(auth, &services::Method::Get, "", &date, &endpoint)?; + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + ]) + } + + fn get_url( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}" + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + logger::debug!(payment_sync_response=?res); + let response: worldline::Payment = res + .response + .parse_struct("Payment") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } +} + +impl api::PaymentCapture for Worldline {} +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Worldline +{ + // Not Implemented +} + +impl api::PaymentSession for Worldline {} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Worldline +{ + // Not Implemented +} + +impl api::PaymentAuthorize for Worldline {} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::PaymentsAuthorizeType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::PaymentsAuthorizeType::get_content_type(self); + let signed_data: String = self.generate_authorization_token( + auth, + &services::Method::Post, + content_type, + &date, + &endpoint, + )?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!("{base_url}v1/{merchat_account_id}/payments")) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let worldline_req = utils::Encode::<worldline::PaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(worldline_req)) + } + + fn build_request( + &self, + req: &types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: worldline::PaymentResponse = res + .response + .parse_struct("PaymentIntentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(worldlinepayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl api::Refund for Worldline {} +impl api::RefundExecute for Worldline {} +impl api::RefundSync for Worldline {} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::RefundExecuteType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let content_type = types::RefundExecuteType::get_content_type(self); + let signed_data: String = self.generate_authorization_token( + auth, + &services::Method::Post, + content_type, + &date, + &endpoint, + )?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + (headers::CONTENT_TYPE.to_string(), content_type.to_string()), + ]) + } + + fn get_content_type(&self) -> &'static str { + "application/json" + } + + fn get_url( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let payment_id = req.request.connector_transaction_id.clone(); + let base_url = self.base_url(connectors); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/payments/{payment_id}/refund" + )) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let refund_req = + utils::Encode::<worldline::WorldlineRefundRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(refund_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + logger::debug!(target: "router::connector::worldline", response=?res); + let response: worldline::RefundResponse = res + .response + .parse_struct("worldline RefundResponse") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Worldline +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let base_url = self.base_url(connectors); + let url = &types::RefundSyncType::get_url(self, req, connectors)?; + let endpoint = url.clone().replace(base_url, ""); + let auth = worldline::AuthType::try_from(&req.connector_auth_type)?; + let date = Self::get_current_date_time()?; + let signed_data: String = + self.generate_authorization_token(auth, &services::Method::Get, "", &date, &endpoint)?; + + Ok(vec![ + (headers::DATE.to_string(), date), + (headers::AUTHORIZATION.to_string(), signed_data), + ]) + } + + fn get_url( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let refund_id = req + .response + .as_ref() + .ok() + .get_required_value("response") + .change_context(errors::ConnectorError::FailedToObtainIntegrationUrl)? + .connector_refund_id + .clone(); + let base_url = self.base_url(connectors); + let auth: worldline::AuthType = worldline::AuthType::try_from(&req.connector_auth_type)?; + let merchat_account_id = auth.merchant_account_id; + Ok(format!( + "{base_url}v1/{merchat_account_id}/refunds/{refund_id}/" + )) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + logger::debug!(target: "router::connector::worldline", response=?res); + let response: worldline::RefundResponse = res + .response + .parse_struct("worldline RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Worldline { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} + +impl services::ConnectorRedirectResponse for Worldline {} diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs new file mode 100644 index 00000000000..0c958a4ffea --- /dev/null +++ b/crates/router/src/connector/worldline/transformers.rs @@ -0,0 +1,487 @@ +use std::collections::HashMap; + +use api_models::payments as api_models; +use common_utils::pii::{self, Email}; +use error_stack::{IntoReport, ResultExt}; +use masking::{PeekInterface, Secret}; +use once_cell::sync::Lazy; +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + types::{self, api, storage::enums}, +}; + +static CARD_REGEX: Lazy<HashMap<CardProduct, Result<Regex, regex::Error>>> = Lazy::new(|| { + let mut map = HashMap::new(); + // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841 + // [#379]: Determine card issuer from card BIN number + map.insert(CardProduct::Master, Regex::new(r"^5[1-5][0-9]{14}$")); + map.insert( + CardProduct::AmericanExpress, + Regex::new(r"^3[47][0-9]{13}$"), + ); + map.insert(CardProduct::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$")); + map.insert(CardProduct::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$")); + map +}); + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Card { + pub card_number: Secret<String, pii::CardNumber>, + pub cardholder_name: Secret<String>, + pub cvv: Secret<String>, + pub expiry_date: Secret<String>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CardPaymentMethod { + pub card: Card, + pub requires_approval: bool, + pub payment_product_id: u16, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AmountOfMoney { + pub amount: i64, + pub currency_code: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Order { + pub amount_of_money: AmountOfMoney, + pub customer: Customer, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BillingAddress { + pub city: Option<String>, + pub country_code: Option<String>, + pub house_number: Option<String>, + pub state: Option<Secret<String>>, + pub state_code: Option<String>, + pub street: Option<String>, + pub zip: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ContactDetails { + pub email_address: Option<Secret<String, Email>>, + pub mobile_phone_number: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Customer { + pub billing_address: BillingAddress, + pub contact_details: Option<ContactDetails>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Name { + pub first_name: Option<Secret<String>>, + pub surname: Option<Secret<String>>, + pub surname_prefix: Option<Secret<String>>, + pub title: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Shipping { + pub city: Option<String>, + pub country_code: Option<String>, + pub house_number: Option<String>, + pub name: Option<Name>, + pub state: Option<Secret<String>>, + pub state_code: Option<String>, + pub street: Option<String>, + pub zip: Option<Secret<String>>, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PaymentsRequest { + pub card_payment_method_specific_input: CardPaymentMethod, + pub order: Order, + pub shipping: Option<Shipping>, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref card) => { + make_card_request(&item.address, &item.request, card) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +fn make_card_request( + address: &types::PaymentAddress, + req: &types::PaymentsAuthorizeData, + ccard: &api_models::CCard, +) -> Result<PaymentsRequest, error_stack::Report<errors::ConnectorError>> { + let card_number = ccard.card_number.peek().as_ref(); + let expiry_year = ccard.card_exp_year.peek().clone(); + let secret_value = format!("{}{}", ccard.card_exp_month.peek(), &expiry_year[2..]); + let expiry_date: Secret<String> = Secret::new(secret_value); + let card = Card { + card_number: ccard.card_number.clone(), + cardholder_name: ccard.card_holder_name.clone(), + cvv: ccard.card_cvc.clone(), + expiry_date, + }; + let payment_product_id = get_card_product_id(card_number)?; + let card_payment_method_specific_input = CardPaymentMethod { + card, + requires_approval: matches!(req.capture_method, Some(enums::CaptureMethod::Manual)), + payment_product_id, + }; + + let customer = build_customer_info(address, &req.email)?; + + let order = Order { + amount_of_money: AmountOfMoney { + amount: req.amount, + currency_code: req.currency.to_string().to_uppercase(), + }, + customer, + }; + + let shipping = address + .shipping + .as_ref() + .and_then(|shipping| shipping.address.clone()) + .map(|address| Shipping { ..address.into() }); + + Ok(PaymentsRequest { + card_payment_method_specific_input, + order, + shipping, + }) +} + +fn get_card_product_id( + card_number: &str, +) -> Result<u16, error_stack::Report<errors::ConnectorError>> { + for (k, v) in CARD_REGEX.iter() { + let regex: Regex = v + .clone() + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + if regex.is_match(card_number) { + return Ok(k.product_id()); + } + } + Err(error_stack::Report::new( + errors::ConnectorError::RequestEncodingFailed, + )) +} + +fn get_address( + payment_address: &types::PaymentAddress, +) -> Option<(&api_models::Address, &api_models::AddressDetails)> { + let billing = payment_address.billing.as_ref()?; + let address = billing.address.as_ref()?; + address.country.as_ref()?; + Some((billing, address)) +} + +fn build_customer_info( + payment_address: &types::PaymentAddress, + email: &Option<Secret<String, Email>>, +) -> Result<Customer, error_stack::Report<errors::ConnectorError>> { + let (billing, address) = + get_address(payment_address).ok_or(errors::ConnectorError::RequestEncodingFailed)?; + + let number_with_country_code = billing.phone.as_ref().and_then(|phone| { + phone.number.as_ref().and_then(|number| { + phone + .country_code + .as_ref() + .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) + }) + }); + + Ok(Customer { + billing_address: BillingAddress { + ..address.clone().into() + }, + contact_details: Some(ContactDetails { + mobile_phone_number: number_with_country_code, + email_address: email.clone(), + }), + }) +} + +impl From<api_models::AddressDetails> for BillingAddress { + fn from(value: api_models::AddressDetails) -> Self { + Self { + city: value.city, + country_code: value.country, + state: value.state, + zip: value.zip, + ..Default::default() + } + } +} + +impl From<api_models::AddressDetails> for Shipping { + fn from(value: api_models::AddressDetails) -> Self { + Self { + city: value.city, + country_code: value.country, + name: Some(Name { + first_name: value.first_name, + surname: value.last_name, + ..Default::default() + }), + state: value.state, + zip: value.zip, + ..Default::default() + } + } +} + +pub struct AuthType { + pub api_key: String, + pub api_secret: String, + pub merchant_account_id: String, +} + +impl TryFrom<&types::ConnectorAuthType> for AuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_string(), + api_secret: api_secret.to_string(), + merchant_account_id: key1.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} + +#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum PaymentStatus { + Captured, + Paid, + ChargebackNotification, + Cancelled, + Rejected, + RejectedCapture, + PendingApproval, + CaptureRequested, + #[default] + Processing, +} + +impl From<PaymentStatus> for enums::AttemptStatus { + fn from(item: PaymentStatus) -> Self { + match item { + PaymentStatus::Captured + | PaymentStatus::Paid + | PaymentStatus::ChargebackNotification => Self::Charged, + PaymentStatus::Cancelled => Self::Voided, + PaymentStatus::Rejected | PaymentStatus::RejectedCapture => Self::Failure, + PaymentStatus::CaptureRequested => Self::CaptureInitiated, + PaymentStatus::PendingApproval => Self::Authorizing, + _ => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct Payment { + id: String, + status: PaymentStatus, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PaymentResponse { + payment: Payment, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.payment.status.clone()), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + connector_metadata: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize)] +pub struct WorldlineRefundRequest { + amount_of_money: AmountOfMoney, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldlineRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount_of_money: AmountOfMoney { + amount: item.request.refund_amount, + currency_code: item.request.currency.to_string(), + }, + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] +pub enum RefundStatus { + Cancelled, + Rejected, + Refunded, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Refunded => Self::Success, + RefundStatus::Cancelled | RefundStatus::Rejected => Self::Failure, + RefundStatus::Processing => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, 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::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.clone(), + refund_status, + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.status); + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.clone(), + refund_status, + }), + ..item.data + }) + } +} + +impl From<&PaymentResponse> for enums::AttemptStatus { + fn from(item: &PaymentResponse) -> Self { + if item.payment.status == PaymentStatus::Cancelled { + Self::Voided + } else { + Self::VoidFailed + } + } +} + +#[derive(Default, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Error { + pub code: Option<String>, + pub property_name: Option<String>, + pub message: Option<String>, +} + +#[derive(Default, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ErrorResponse { + pub error_id: Option<String>, + pub errors: Vec<Error>, +} + +#[derive(Debug, Eq, Hash, PartialEq)] +pub enum CardProduct { + AmericanExpress, + Master, + Visa, + Discover, +} + +impl CardProduct { + fn product_id(&self) -> u16 { + match *self { + Self::AmericanExpress => 2, + Self::Master => 3, + Self::Visa => 1, + Self::Discover => 128, + } + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 899969d55d4..f506f242dc9 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -242,6 +242,8 @@ pub enum ConnectorError { WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, + #[error("Invalid Date/time format")] + InvalidDateFormat, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index e130a70707c..becbecdaeb5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -47,6 +47,7 @@ pub mod headers { pub const AUTHORIZATION: &str = "Authorization"; pub const ACCEPT: &str = "Accept"; pub const X_API_VERSION: &str = "X-ApiVersion"; + pub const DATE: &str = "Date"; } pub mod pii { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a14ad31c1d6..0c21a8a45ca 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -152,6 +152,7 @@ impl ConnectorData { "payu" => Ok(Box::new(&connector::Payu)), "shift4" => Ok(Box::new(&connector::Shift4)), "stripe" => Ok(Box::new(&connector::Stripe)), + "worldline" => Ok(Box::new(&connector::Worldline)), "worldpay" => Ok(Box::new(&connector::Worldpay)), _ => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 2237f0994d2..9bb2cabdcc3 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -11,6 +11,7 @@ pub(crate) struct ConnectorAuthentication { pub payu: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub worldpay: Option<HeaderKey>, + pub worldline: Option<SignatureKey>, } impl ConnectorAuthentication { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 3d5af329ed7..39bb16e7a4b 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -9,4 +9,5 @@ mod globalpay; mod payu; mod shift4; mod utils; +mod worldline; mod worldpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 463e6460b54..a161b71c078 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -31,3 +31,7 @@ api_key = "MyApiKey" key1 = "MerchantID" api_secret = "MySecretKey" +[worldline] +key1 = "Merchant Id" +api_key = "API Key" +api_secret = "API Secret Key" \ No newline at end of file diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs new file mode 100644 index 00000000000..c8aa01549e1 --- /dev/null +++ b/crates/router/tests/connectors/worldline.rs @@ -0,0 +1,278 @@ +use api_models::payments::{Address, AddressDetails}; +use masking::Secret; +use router::{ + connector::Worldline, + types::{self, storage::enums, PaymentAddress}, +}; + +use crate::{ + connector_auth::ConnectorAuthentication, + utils::{self, ConnectorActions, PaymentInfo}, +}; + +struct WorldlineTest; + +impl ConnectorActions for WorldlineTest {} +impl utils::Connector for WorldlineTest { + fn get_data(&self) -> types::api::ConnectorData { + types::api::ConnectorData { + connector: Box::new(&Worldline), + connector_name: types::Connector::Worldline, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + ConnectorAuthentication::new() + .worldline + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + String::from("worldline") + } +} + +impl WorldlineTest { + fn get_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(PaymentAddress { + billing: Some(Address { + address: Some(AddressDetails { + country: Some("US".to_string()), + ..Default::default() + }), + phone: None, + }), + ..Default::default() + }), + auth_type: None, + }) + } + + fn get_payment_authorize_data( + card_number: &str, + card_exp_month: &str, + card_exp_year: &str, + card_cvc: &str, + capture_method: enums::CaptureMethod, + ) -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + amount: 3500, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethod::Card(types::api::CCard { + card_number: Secret::new(card_number.to_string()), + card_exp_month: Secret::new(card_exp_month.to_string()), + card_exp_year: Secret::new(card_exp_year.to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new(card_cvc.to_string()), + }), + confirm: true, + statement_descriptor_suffix: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + }) + } +} + +#[actix_web::test] +async fn should_requires_manual_authorization() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); +} + +#[actix_web::test] +async fn should_auto_authorize_and_request_capture() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); +} + +#[actix_web::test] +async fn should_fail_payment_for_invalid_cvc() { + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "", + enums::CaptureMethod::Automatic, + ); + let response = WorldlineTest {} + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!( + response.response.unwrap_err().message, + "NULL VALUE NOT ALLOWED FOR cardPaymentMethodSpecificInput.card.cvv".to_string(), + ); +} + +#[actix_web::test] +async fn should_sync_manual_auth_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_payment_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::Authorizing); +} + +#[actix_web::test] +async fn should_sync_auto_auth_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let sync_response = connector + .sync_payment( + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_payment_id, + ), + encoded_data: None, + }), + None, + ) + .await; + assert_eq!(sync_response.status, enums::AttemptStatus::CaptureInitiated); +} + +#[actix_web::test] +async fn should_fail_capture_payment() { + let capture_response = WorldlineTest {} + .capture_payment("123456789".to_string(), None, None) + .await; + assert_eq!( + capture_response.response.unwrap_err().message, + "Something went wrong.".to_string() + ); +} + +#[actix_web::test] +async fn should_cancel_unauthorized_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let cancel_response = connector + .void_payment(connector_payment_id, None, None) + .await; + assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); +} + +#[actix_web::test] +async fn should_cancel_uncaptured_payment() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Automatic, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let cancel_response = connector + .void_payment(connector_payment_id, None, None) + .await; + assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); +} + +#[actix_web::test] +async fn should_fail_cancel_with_invalid_payment_id() { + let response = WorldlineTest {} + .void_payment("123456789".to_string(), None, None) + .await; + assert_eq!( + response.response.unwrap_err().message, + "UNKNOWN_PAYMENT_ID".to_string(), + ); +} + +#[actix_web::test] +async fn should_fail_refund_with_invalid_payment_status() { + let connector = WorldlineTest {}; + let authorize_data = WorldlineTest::get_payment_authorize_data( + "4012000033330026", + "10", + "2025", + "123", + enums::CaptureMethod::Manual, + ); + let response = connector + .make_payment(authorize_data, WorldlineTest::get_payment_info()) + .await; + assert_eq!(response.status, enums::AttemptStatus::Authorizing); + let connector_payment_id = utils::get_connector_transaction_id(response).unwrap_or_default(); + let refund_response = connector + .refund_payment(connector_payment_id, None, None) + .await; + assert_eq!( + refund_response.response.unwrap_err().message, + "ORDER WITHOUT REFUNDABLE PAYMENTS".to_string(), + ); +}
feature
add support for worldline connector (#374)
937aea906e759e6e8a76a424db99ed052d46b7d2
2024-01-30 12:53:58
harsh-sharma-juspay
chore(analytics): adding dispute id to api log events (#3450)
false
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql index 0fe194a0e67..ad0fe6d778f 100644 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql @@ -18,7 +18,8 @@ CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' ( `created_at` DateTime CODEC(T64, LZ4), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -81,7 +82,8 @@ CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' ( `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand()); CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist ( @@ -105,7 +107,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyp `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -158,7 +161,7 @@ WHERE length(_error) > 0 ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String)); ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String)); - +ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `dispute_id` Nullable(String); CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' ( `merchant_id` LowCardinality(String), @@ -209,7 +212,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -232,6 +236,7 @@ SELECT created_at, latency, user_agent, - ip_addr + ip_addr, + dispute_id FROM hyperswitch.api_events_queue WHERE length(_error) = 0 \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/api_events.sql b/crates/analytics/docs/clickhouse/scripts/api_events.sql index c3fc3d7b06d..49a6472eaa4 100644 --- a/crates/analytics/docs/clickhouse/scripts/api_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/api_events.sql @@ -23,7 +23,8 @@ CREATE TABLE api_events_queue ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -57,6 +58,7 @@ CREATE TABLE api_events_dist ( `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), `url_path` String, + `dispute_id` Nullable(String) INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -92,7 +94,8 @@ CREATE MATERIALIZED VIEW api_events_mv TO api_events_dist ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -120,7 +123,8 @@ SELECT ip_addr, hs_latency, http_method, - url_path + url_path, + dispute_id FROM api_events_queue where length(_error) = 0; diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index a8185d2d241..ae0525ac609 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -1,5 +1,6 @@ pub mod connector_onboarding; pub mod customer; +pub mod dispute; pub mod gsm; mod locker_migration; pub mod payment; @@ -44,8 +45,6 @@ impl_misc_api_event_type!( RetrievePaymentLinkResponse, MandateListConstraints, CreateFileResponse, - DisputeResponse, - SubmitEvidenceRequest, MerchantConnectorResponse, MerchantConnectorId, MandateResponse, diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs new file mode 100644 index 00000000000..101dba3ca02 --- /dev/null +++ b/crates/api_models/src/events/dispute.rs @@ -0,0 +1,25 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use super::{DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest}; + +impl ApiEventMetric for SubmitEvidenceRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponsePaymentsRetrieve { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index c2bf50d96c3..e755e0f9c4c 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -50,6 +50,9 @@ pub enum ApiEventsType { RustLocker, FraudCheck, Recon, + Dispute { + dispute_id: String, + }, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 78a66d2f04e..3d74a028840 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -114,7 +114,6 @@ impl_misc_api_event_type!( CreateFileRequest, FileId, AttachEvidenceRequest, - DisputeId, PaymentLinkFormData, ConfigUpdate ); @@ -142,3 +141,11 @@ impl ApiEventMetric for PaymentsRedirectResponseData { }) } } + +impl ApiEventMetric for DisputeId { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +}
chore
adding dispute id to api log events (#3450)
eff280f2fbaba392a61d6f55fb251de106273a41
2023-09-12 20:12:42
Narayan Bhat
fix(webhooks): fix database queries in webhook (#2139)
false
diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs index d849f1f82ef..a765f8adc7f 100644 --- a/crates/router/src/types/api/webhooks.rs +++ b/crates/router/src/types/api/webhooks.rs @@ -103,7 +103,7 @@ pub trait IncomingWebhook: ConnectorCommon + Sync { let merchant_connector_account_result = db .find_merchant_connector_account_by_profile_id_connector_name( &profile_id, - &merchant_account.merchant_id, + connector_name, key_store, ) .await; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 4ac092125ac..b9e4504a992 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -27,7 +27,10 @@ use uuid::Uuid; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, - core::errors::{self, CustomResult, RouterResult, StorageErrorExt}, + core::{ + errors::{self, CustomResult, RouterResult, StorageErrorExt}, + utils, + }, db::StorageInterface, logger, routes::metrics, @@ -305,14 +308,18 @@ pub async fn get_profile_id_using_object_reference_id( .await? } }; - let profile_id = payment_intent - .profile_id - .ok_or(errors::ApiErrorResponse::MissingRequiredField { - field_name: "business_profile", - }) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + + let profile_id = utils::get_profile_id_from_business_details( + payment_intent.business_country, + payment_intent.business_label.as_ref(), + merchant_account, + payment_intent.profile_id.as_ref(), + db, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")?; + Ok(profile_id) } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 332dc3f8dcf..7b64cd012f7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -226,8 +226,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { async fn find_payment_attempt_by_attempt_id_merchant_id( &self, - merchant_id: &str, attempt_id: &str, + merchant_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?;
fix
fix database queries in webhook (#2139)
400d9a42de4cb99e3e2d7dc69510f503661700e4
2024-12-11 05:52:31
github-actions
chore(version): 2024.12.11.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a8a4155e14..3325b502999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,41 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.12.11.0 + +### Features + +- **analytics:** Add support for multiple emails as input to forward reports ([#6776](https://github.com/juspay/hyperswitch/pull/6776)) ([`3df4233`](https://github.com/juspay/hyperswitch/commit/3df42333566b646e9ca93d612a78ea8d38298df4)) +- **connector:** [Unifiedauthenticationservice] add Connector Template Code ([#6732](https://github.com/juspay/hyperswitch/pull/6732)) ([`8777f41`](https://github.com/juspay/hyperswitch/commit/8777f41568ebf5373917089d7d42f3b14fb1bf60)) +- **payments:** [Payment links] Add locale case fix ([#6789](https://github.com/juspay/hyperswitch/pull/6789)) ([`8431842`](https://github.com/juspay/hyperswitch/commit/84318427108a0f974b2519587d0e336807a9600c)) + +### Bug Fixes + +- **core:** + - Add validation to check if routable connector supports network tokenization in CIT repeat flow ([#6749](https://github.com/juspay/hyperswitch/pull/6749)) ([`9f0d8ef`](https://github.com/juspay/hyperswitch/commit/9f0d8efa8dad45a773f4cab6978288f2209e4abf)) + - Payments - map billing first and last name to card holder name ([#6791](https://github.com/juspay/hyperswitch/pull/6791)) ([`c3b22cf`](https://github.com/juspay/hyperswitch/commit/c3b22cf81a5c8cbc6538ca7f7e4b1ce4d18eb644)) +- **docs:** Incorrect description for refund api ([#6443](https://github.com/juspay/hyperswitch/pull/6443)) ([`8954e8a`](https://github.com/juspay/hyperswitch/commit/8954e8a2180d20719b1bb0d4f77081ff03fd9b43)) + +### Refactors + +- **constraint_graph:** Add setup_future_usage for mandate check in payments ([#6744](https://github.com/juspay/hyperswitch/pull/6744)) ([`1aa4ad6`](https://github.com/juspay/hyperswitch/commit/1aa4ad60e2326cbdc5c81479cf3420c3f3e1d8ee)) +- **enums:** Recon - include ReconOps variant in PermissionsGroup for backwards compatibility with data in DB ([#6767](https://github.com/juspay/hyperswitch/pull/6767)) ([`a528282`](https://github.com/juspay/hyperswitch/commit/a52828296a682e30badf0849921469cdf4eecbea)) +- **events:** Tenant config in API, Connector and Outgoing Web-hook events ([#6777](https://github.com/juspay/hyperswitch/pull/6777)) ([`c620779`](https://github.com/juspay/hyperswitch/commit/c620779bbd14a1102d4fff68cc36581935d87da7)) +- **payment_methods:** Add new field_type UserBsbNumber, UserBankSortCode and UserBankRoutingNumber for payment_connector_required_fields ([#6758](https://github.com/juspay/hyperswitch/pull/6758)) ([`6f84145`](https://github.com/juspay/hyperswitch/commit/6f841458f73cec8ce43a34b1b50abbc74baa2ef7)) +- **users:** Remove lineage checks in roles get operations ([#6701](https://github.com/juspay/hyperswitch/pull/6701)) ([`f96a87d`](https://github.com/juspay/hyperswitch/commit/f96a87d08ca003411d63dcd9ef4dda6439d20e07)) + +### Documentation + +- Add new logos for README and API reference ([#6783](https://github.com/juspay/hyperswitch/pull/6783)) ([`b9c04c3`](https://github.com/juspay/hyperswitch/commit/b9c04c39880aa1ab0b66397802d138f0d4c1ed28)) + +### Build System / Dependencies + +- **deps:** Bump opentelemetry crates to 0.27 ([#6774](https://github.com/juspay/hyperswitch/pull/6774)) ([`47a3d2b`](https://github.com/juspay/hyperswitch/commit/47a3d2b2abcc28a13f79bd9318d119f103b7fb6c)) + +**Full Changelog:** [`2024.12.10.0...2024.12.11.0`](https://github.com/juspay/hyperswitch/compare/2024.12.10.0...2024.12.11.0) + +- - - + ## 2024.12.10.0 ### Features
chore
2024.12.11.0
ca72fedae82194abb7216854c7dd61c64d57b1d6
2024-08-22 10:30:07
Mani Chandra
feat(user_role): Add update by lineage DB function (#5651)
false
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index b84ea63de1d..b7f79a4438f 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -41,47 +41,6 @@ impl UserRole { .await } - pub async fn update_by_user_id_merchant_id( - conn: &PgPooledConn, - user_id: String, - merchant_id: id_type::MerchantId, - update: UserRoleUpdate, - version: UserRoleVersion, - ) -> StorageResult<Self> { - generics::generic_update_with_unique_predicate_get_result::< - <Self as HasTable>::Table, - _, - _, - _, - >( - conn, - dsl::user_id - .eq(user_id) - .and(dsl::merchant_id.eq(merchant_id)) - .and(dsl::version.eq(version)), - UserRoleUpdateInternal::from(update), - ) - .await - } - - pub async fn update_by_user_id_org_id( - conn: &PgPooledConn, - user_id: String, - org_id: id_type::OrganizationId, - update: UserRoleUpdate, - version: UserRoleVersion, - ) -> StorageResult<Vec<Self>> { - generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( - conn, - dsl::user_id - .eq(user_id) - .and(dsl::org_id.eq(org_id)) - .and(dsl::version.eq(version)), - UserRoleUpdateInternal::from(update), - ) - .await - } - pub async fn list_by_user_id( conn: &PgPooledConn, user_id: String, @@ -147,6 +106,46 @@ impl UserRole { generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await } + pub async fn update_by_user_id_org_id_merchant_id_profile_id( + conn: &PgPooledConn, + user_id: String, + org_id: id_type::OrganizationId, + merchant_id: id_type::MerchantId, + profile_id: Option<String>, + update: UserRoleUpdate, + version: UserRoleVersion, + ) -> StorageResult<Self> { + // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level + // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?) + let check_lineage = dsl::org_id + .eq(org_id.clone()) + .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null())) + .or(dsl::org_id.eq(org_id.clone()).and( + dsl::merchant_id + .eq(merchant_id.clone()) + .and(dsl::profile_id.is_null()), + )) + .or(dsl::org_id.eq(org_id).and( + dsl::merchant_id + .eq(merchant_id) + //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option + .and(dsl::profile_id.eq(profile_id)), + )); + + let predicate = dsl::user_id + .eq(user_id) + .and(check_lineage) + .and(dsl::version.eq(version)); + + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + UserRoleUpdateInternal, + _, + _, + >(conn, predicate, update.into()) + .await + } + pub async fn delete_by_user_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 87e6f332328..1a006f2a4ad 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -51,6 +51,7 @@ pub struct UserRoleUpdateInternal { last_modified: PrimitiveDateTime, } +#[derive(Clone)] pub enum UserRoleUpdate { UpdateStatus { status: enums::UserStatus, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 042e2c19e7c..671d3ee1535 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -594,19 +594,58 @@ pub async fn reset_password( .change_context(UserErrors::InternalServerError)?; if let Some(inviter_merchant_id) = email_token.get_merchant_id() { - let update_status_result = state + let key_manager_state = &(&state).into(); + + let key_store = state .store - .update_user_role_by_user_id_merchant_id( + .get_merchant_key_store_by_merchant_id( + key_manager_state, + inviter_merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_key_store not found")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + inviter_merchant_id, + &key_store, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_account not found")?; + + let (update_v1_result, update_v2_result) = + utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, user.user_id.clone().as_str(), + &merchant_account.organization_id, inviter_merchant_id, + None, UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user.user_id.clone(), }, - UserRoleVersion::V1, ) .await; - logger::info!(?update_status_result); + + if update_v1_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + { + return Err(report!(UserErrors::InternalServerError)); + } + + if update_v1_result.is_err() && update_v2_result.is_err() { + return Err(report!(UserErrors::InvalidRoleOperation)) + .attach_printable("User not found in the organization")?; + } } let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) @@ -1014,19 +1053,53 @@ pub async fn accept_invite_from_email( .get_merchant_id() .ok_or(UserErrors::InternalServerError)?; - let update_status_result = state + let key_manager_state = &(&state).into(); + + let key_store = state .store - .update_user_role_by_user_id_merchant_id( - user.get_user_id(), + .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user.get_user_id().to_string(), - }, - UserRoleVersion::V1, + &state.store.get_master_key().to_vec().into(), ) .await - .change_context(UserErrors::InternalServerError)?; + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_key_store not found")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_account not found")?; + + let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, + user.get_user_id(), + &merchant_account.organization_id, + merchant_id, + None, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user.get_user_id().to_string(), + }, + ) + .await; + + if update_v1_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + { + return Err(report!(UserErrors::InternalServerError)); + } + + if update_v1_result.is_err() && update_v2_result.is_err() { + return Err(report!(UserErrors::InvalidRoleOperation)) + .attach_printable("User not found in the organization")?; + } let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await @@ -1039,21 +1112,18 @@ pub async fn accept_invite_from_email( .change_context(UserErrors::InternalServerError)? .into(); - let token = utils::user::generate_jwt_auth_token_without_profile( - &state, - &user_from_db, - &update_status_result, - ) - .await?; - utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result) - .await; + let user_role = user_from_db + .get_preferred_or_active_user_role_from_db(&state) + .await + .change_context(UserErrors::InternalServerError)?; - let response = utils::user::get_dashboard_entry_response( - &state, - user_from_db, - update_status_result, - token.clone(), - )?; + let token = + utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role) + .await?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; + + let response = + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; auth::cookies::set_cookie_response(response, token) } @@ -1091,19 +1161,53 @@ pub async fn accept_invite_from_email_token_only_flow( .get_merchant_id() .ok_or(UserErrors::LinkInvalid)?; - let user_role = state + let key_manager_state = &(&state).into(); + + let key_store = state .store - .update_user_role_by_user_id_merchant_id( - user_from_db.get_user_id(), + .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_from_db.get_user_id().to_string(), - }, - UserRoleVersion::V1, + &state.store.get_master_key().to_vec().into(), ) .await - .change_context(UserErrors::InternalServerError)?; + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_key_store not found")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("merchant_account not found")?; + + let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, + user_from_db.get_user_id(), + &merchant_account.organization_id, + merchant_id, + None, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_from_db.get_user_id().to_owned(), + }, + ) + .await; + + if update_v1_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result + .as_ref() + .is_err_and(|err| !err.current_context().is_db_not_found()) + { + return Err(report!(UserErrors::InternalServerError)); + } + + if update_v1_result.is_err() && update_v2_result.is_err() { + return Err(report!(UserErrors::InvalidRoleOperation)) + .attach_printable("User not found in the organization")?; + } if !user_from_db.is_verified() { let _ = state @@ -1126,6 +1230,11 @@ pub async fn accept_invite_from_email_token_only_flow( )?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; + let user_role = user_from_db + .get_preferred_or_active_user_role_from_db(&state) + .await + .change_context(UserErrors::InternalServerError)?; + let token = next_flow .get_token_with_user_role(&state, &user_role) .await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index d9ee8f21805..b599a26fdfc 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -7,10 +7,8 @@ use diesel_models::{ }; use error_stack::{report, ResultExt}; use once_cell::sync::Lazy; -use router_env::logger; use crate::{ - consts, core::errors::{StorageErrorExt, UserErrors, UserResponse}, routes::{app::ReqState, SessionState}, services::{ @@ -115,103 +113,155 @@ pub async fn update_user_role( .attach_printable("User Changing their own role"); } - let user_role_to_be_updated = user_to_be_updated - .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id) - .await - .to_not_found_response(UserErrors::InvalidRoleOperation)?; - - let role_to_be_updated = roles::RoleInfo::from_role_id( + let updator_role = roles::RoleInfo::from_role_id( &state, - &user_role_to_be_updated.role_id, + &user_from_token.role_id, &user_from_token.merchant_id, &user_from_token.org_id, ) .await .change_context(UserErrors::InternalServerError)?; - if !role_to_be_updated.is_updatable() { - return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( - "User role cannot be updated from {}", - role_to_be_updated.get_role_id() - )); - } + let mut is_updated = false; - state + let v2_user_role_to_be_updated = match state .store - .update_user_role_by_user_id_merchant_id( + .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), - &user_role_to_be_updated - .merchant_id - .ok_or(UserErrors::InternalServerError) - .attach_printable("merchant_id not found in user_role")?, - UserRoleUpdate::UpdateRole { - role_id: req.role_id.clone(), - modified_by: user_from_token.user_id, - }, - UserRoleVersion::V1, + &user_from_token.org_id, + &user_from_token.merchant_id, + None, + UserRoleVersion::V2, ) .await - .to_not_found_response(UserErrors::InvalidRoleOperation) - .attach_printable("User with given email is not found in the organization")?; + { + Ok(user_role) => Some(user_role), + Err(e) => { + if e.current_context().is_db_not_found() { + None + } else { + return Err(UserErrors::InternalServerError.into()); + } + } + }; - auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; + if let Some(user_role) = v2_user_role_to_be_updated { + let role_to_be_updated = roles::RoleInfo::from_role_id( + &state, + &user_role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; - Ok(ApplicationResponse::StatusOk) -} + if !role_to_be_updated.is_updatable() { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "User role cannot be updated from {}", + role_to_be_updated.get_role_id() + )); + } -pub async fn transfer_org_ownership( - state: SessionState, - user_from_token: auth::UserFromToken, - req: user_role_api::TransferOrgOwnershipRequest, - _req_state: ReqState, -) -> UserResponse<user_api::DashboardEntryResponse> { - if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN { - return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( - "role_id = {} is not org_admin", - user_from_token.role_id - )); - } + if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "Invalid operation, update requestor = {} cannot update target = {}", + updator_role.get_entity_type(), + role_to_be_updated.get_entity_type() + )); + } - let user_to_be_updated = - utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) + state + .store + .update_user_role_by_user_id_and_lineage( + user_to_be_updated.get_user_id(), + &user_from_token.org_id, + &user_from_token.merchant_id, + None, + UserRoleUpdate::UpdateRole { + role_id: req.role_id.clone(), + modified_by: user_from_token.user_id.clone(), + }, + UserRoleVersion::V2, + ) .await - .to_not_found_response(UserErrors::InvalidRoleOperation) - .attach_printable("User not found in our records".to_string())?; + .change_context(UserErrors::InternalServerError)?; - if user_from_token.user_id == user_to_be_updated.get_user_id() { - return Err(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("User transferring ownership to themselves".to_string()); + is_updated = true; } - state + let v1_user_role_to_be_updated = match state .store - .transfer_org_ownership_between_users( - &user_from_token.user_id, + .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), &user_from_token.org_id, + &user_from_token.merchant_id, + None, UserRoleVersion::V1, ) .await + { + Ok(user_role) => Some(user_role), + Err(e) => { + if e.current_context().is_db_not_found() { + None + } else { + return Err(UserErrors::InternalServerError.into()); + } + } + }; + + if let Some(user_role) = v1_user_role_to_be_updated { + let role_to_be_updated = roles::RoleInfo::from_role_id( + &state, + &user_role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await .change_context(UserErrors::InternalServerError)?; - auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; - auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; + if !role_to_be_updated.is_updatable() { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "User role cannot be updated from {}", + role_to_be_updated.get_role_id() + )); + } - let user_from_db = user_from_token.get_user_from_db(&state).await?; - let user_role = user_from_db - .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id) - .await - .to_not_found_response(UserErrors::InvalidRoleOperation)?; + if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "Invalid operation, update requestor = {} cannot update target = {}", + updator_role.get_entity_type(), + role_to_be_updated.get_entity_type() + )); + } - utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; + state + .store + .update_user_role_by_user_id_and_lineage( + user_to_be_updated.get_user_id(), + &user_from_token.org_id, + &user_from_token.merchant_id, + None, + UserRoleUpdate::UpdateRole { + role_id: req.role_id.clone(), + modified_by: user_from_token.user_id, + }, + UserRoleVersion::V1, + ) + .await + .change_context(UserErrors::InternalServerError)?; - let token = - utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role) - .await?; - let response = - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?; + is_updated = true; + } - auth::cookies::set_cookie_response(response, token) + if !is_updated { + return Err(report!(UserErrors::InvalidRoleOperation)) + .attach_printable("User with given email is not found in the organization")?; + } + + auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; + + Ok(ApplicationResponse::StatusOk) } pub async fn accept_invitation( @@ -219,30 +269,43 @@ pub async fn accept_invitation( user_token: auth::UserFromToken, req: user_role_api::AcceptInvitationRequest, ) -> UserResponse<()> { - futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { - state - .store - .update_user_role_by_user_id_merchant_id( - user_token.user_id.as_str(), - merchant_id, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_token.user_id.clone(), - }, - UserRoleVersion::V1, - ) - .await - .map_err(|e| { - logger::error!("Error while accepting invitation {e:?}"); - }) - .ok() - })) - .await - .into_iter() - .reduce(Option::or) - .flatten() - .ok_or(UserErrors::MerchantIdNotFound.into()) - .map(|_| ApplicationResponse::StatusOk) + let merchant_accounts = state + .store + .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids) + .await + .change_context(UserErrors::InternalServerError)?; + + let update_result = + futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async { + let (update_v1_result, update_v2_result) = + utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, + user_token.user_id.as_str(), + &merchant_account.organization_id, + merchant_account.get_id(), + None, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_token.user_id.clone(), + }, + ) + .await; + + if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) + { + Err(report!(UserErrors::InternalServerError)) + } else { + Ok(()) + } + })) + .await; + + if update_result.iter().all(Result::is_err) { + return Err(UserErrors::MerchantIdNotFound.into()); + } + + Ok(ApplicationResponse::StatusOk) } pub async fn merchant_select( @@ -250,38 +313,55 @@ pub async fn merchant_select( user_token: auth::UserFromSinglePurposeToken, req: user_role_api::MerchantSelectRequest, ) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> { - let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { - state - .store - .update_user_role_by_user_id_merchant_id( - user_token.user_id.as_str(), - merchant_id, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_token.user_id.clone(), - }, - UserRoleVersion::V1, - ) - .await - .map_err(|e| { - logger::error!("Error while accepting invitation {e:?}"); - }) - .ok() - })) - .await - .into_iter() - .reduce(Option::or) - .flatten() - .ok_or(UserErrors::MerchantIdNotFound)?; + let merchant_accounts = state + .store + .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids) + .await + .change_context(UserErrors::InternalServerError)?; + + let update_result = + futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async { + let (update_v1_result, update_v2_result) = + utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, + user_token.user_id.as_str(), + &merchant_account.organization_id, + merchant_account.get_id(), + None, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_token.user_id.clone(), + }, + ) + .await; + + if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) + { + Err(report!(UserErrors::InternalServerError)) + } else { + Ok(()) + } + })) + .await; + + if update_result.iter().all(Result::is_err) { + return Err(UserErrors::MerchantIdNotFound.into()); + } if let Some(true) = req.need_dashboard_entry_response { - let user_from_db = state + let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(user_token.user_id.as_str()) .await .change_context(UserErrors::InternalServerError)? .into(); + let user_role = user_from_db + .get_preferred_or_active_user_role_from_db(&state) + .await + .change_context(UserErrors::InternalServerError)?; + utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await; let token = @@ -307,29 +387,41 @@ pub async fn merchant_select_token_only_flow( user_token: auth::UserFromSinglePurposeToken, req: user_role_api::MerchantSelectRequest, ) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> { - let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { - state - .store - .update_user_role_by_user_id_merchant_id( - user_token.user_id.as_str(), - merchant_id, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_token.user_id.clone(), - }, - UserRoleVersion::V1, - ) - .await - .map_err(|e| { - logger::error!("Error while accepting invitation {e:?}"); - }) - .ok() - })) - .await - .into_iter() - .reduce(Option::or) - .flatten() - .ok_or(UserErrors::MerchantIdNotFound)?; + let merchant_accounts = state + .store + .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids) + .await + .change_context(UserErrors::InternalServerError)?; + + let update_result = + futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async { + let (update_v1_result, update_v2_result) = + utils::user_role::update_v1_and_v2_user_roles_in_db( + &state, + user_token.user_id.as_str(), + &merchant_account.organization_id, + merchant_account.get_id(), + None, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_token.user_id.clone(), + }, + ) + .await; + + if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) + || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) + { + Err(report!(UserErrors::InternalServerError)) + } else { + Ok(()) + } + })) + .await; + + if update_result.iter().all(Result::is_err) { + return Err(UserErrors::MerchantIdNotFound.into()); + } let user_from_db: domain::UserFromStorage = state .global_store @@ -338,6 +430,11 @@ pub async fn merchant_select_token_only_flow( .change_context(UserErrors::InternalServerError)? .into(); + let user_role = user_from_db + .get_preferred_or_active_user_role_from_db(&state) + .await + .change_context(UserErrors::InternalServerError)?; + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 21f69d5515c..c22f327983a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2793,30 +2793,6 @@ impl UserRoleInterface for KafkaStore { .await } - async fn update_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - update: user_storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<user_storage::UserRole, errors::StorageError> { - self.diesel_store - .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update, version) - .await - } - - async fn update_user_roles_by_user_id_org_id( - &self, - user_id: &str, - org_id: &id_type::OrganizationId, - update: user_storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { - self.diesel_store - .update_user_roles_by_user_id_org_id(user_id, org_id, update, version) - .await - } - async fn list_user_roles_by_user_id( &self, user_id: &str, @@ -2846,34 +2822,43 @@ impl UserRoleInterface for KafkaStore { .await } - async fn delete_user_role_by_user_id_and_lineage( + async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: Option<&String>, + update: user_storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store - .delete_user_role_by_user_id_and_lineage( + .update_user_role_by_user_id_and_lineage( user_id, org_id, merchant_id, profile_id, + update, version, ) .await } - async fn transfer_org_ownership_between_users( + async fn delete_user_role_by_user_id_and_lineage( &self, - from_user_id: &str, - to_user_id: &str, + user_id: &str, org_id: &id_type::OrganizationId, + merchant_id: &id_type::MerchantId, + profile_id: Option<&String>, version: enums::UserRoleVersion, - ) -> CustomResult<(), errors::StorageError> { + ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store - .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id, version) + .delete_user_role_by_user_id_and_lineage( + user_id, + org_id, + merchant_id, + profile_id, + version, + ) .await } diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index 05f37d0ee72..a93aeb1ce34 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -1,6 +1,3 @@ -use std::collections::HashSet; - -use async_bb8_diesel::AsyncConnection; use common_utils::id_type; use diesel_models::{enums, user_role as storage}; use error_stack::{report, ResultExt}; @@ -8,7 +5,7 @@ use router_env::{instrument, tracing}; use super::MockDb; use crate::{ - connection, consts, + connection, core::errors::{self, CustomResult}, services::Store, }; @@ -33,22 +30,6 @@ pub trait UserRoleInterface { version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; - async fn update_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn update_user_roles_by_user_id_org_id( - &self, - user_id: &str, - org_id: &id_type::OrganizationId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; - async fn list_user_roles_by_user_id( &self, user_id: &str, @@ -70,22 +51,24 @@ pub trait UserRoleInterface { version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; - async fn delete_user_role_by_user_id_and_lineage( + async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: Option<&String>, + update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; - async fn transfer_org_ownership_between_users( + async fn delete_user_role_by_user_id_and_lineage( &self, - from_user_id: &str, - to_user_id: &str, + user_id: &str, org_id: &id_type::OrganizationId, + merchant_id: &id_type::MerchantId, + profile_id: Option<&String>, version: enums::UserRoleVersion, - ) -> CustomResult<(), errors::StorageError>; + ) -> CustomResult<storage::UserRole, errors::StorageError>; } #[async_trait::async_trait] @@ -132,46 +115,6 @@ impl UserRoleInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } - #[instrument(skip_all)] - async fn update_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::update_by_user_id_merchant_id( - &conn, - user_id.to_owned(), - merchant_id.to_owned(), - update, - version, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn update_user_roles_by_user_id_org_id( - &self, - user_id: &str, - org_id: &id_type::OrganizationId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::update_by_user_id_org_id( - &conn, - user_id.to_owned(), - org_id.to_owned(), - update, - version, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - #[instrument(skip_all)] async fn list_user_roles_by_user_id( &self, @@ -219,21 +162,23 @@ impl UserRoleInterface for Store { } #[instrument(skip_all)] - async fn delete_user_role_by_user_id_and_lineage( + async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: Option<&String>, + update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id( + storage::UserRole::update_by_user_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.cloned(), + update, version, ) .await @@ -241,97 +186,25 @@ impl UserRoleInterface for Store { } #[instrument(skip_all)] - async fn transfer_org_ownership_between_users( + async fn delete_user_role_by_user_id_and_lineage( &self, - from_user_id: &str, - to_user_id: &str, + user_id: &str, org_id: &id_type::OrganizationId, + merchant_id: &id_type::MerchantId, + profile_id: Option<&String>, version: enums::UserRoleVersion, - ) -> CustomResult<(), errors::StorageError> { - let conn = connection::pg_connection_write(self) - .await - .change_context(errors::StorageError::DatabaseConnectionError)?; - - conn.transaction_async(|conn| async move { - let old_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id( - &conn, - from_user_id.to_owned(), - org_id.to_owned(), - storage::UserRoleUpdate::UpdateRole { - role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), - modified_by: from_user_id.to_owned(), - }, - version, - ) - .await - .map_err(|e| *e.current_context())?; - - let new_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id( - &conn, - to_user_id.to_owned(), - org_id.to_owned(), - storage::UserRoleUpdate::UpdateRole { - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - modified_by: from_user_id.to_owned(), - }, - version, - ) - .await - .map_err(|e| *e.current_context())?; - - let new_org_admin_merchant_ids = new_org_admin_user_roles - .iter() - .map(|user_role| { - user_role - .merchant_id - .to_owned() - .ok_or(errors::DatabaseError::Others) - }) - .collect::<Result<HashSet<_>, _>>()?; - - let now = common_utils::date_time::now(); - - let mut missing_new_user_roles = Vec::new(); - - for old_role in old_org_admin_user_roles { - let Some(old_role_merchant_id) = &old_role.merchant_id else { - return Err(errors::DatabaseError::Others); - }; - if !new_org_admin_merchant_ids.contains(old_role_merchant_id) { - missing_new_user_roles.push(storage::UserRoleNew { - user_id: to_user_id.to_string(), - merchant_id: Some(old_role_merchant_id.to_owned()), - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - org_id: Some(org_id.to_owned()), - status: enums::UserStatus::Active, - created_by: from_user_id.to_string(), - last_modified_by: from_user_id.to_string(), - created_at: now, - last_modified: now, - profile_id: None, - entity_id: None, - entity_type: None, - version: enums::UserRoleVersion::V1, - }); - } - } - - futures::future::try_join_all(missing_new_user_roles.into_iter().map( - |user_role| async { - user_role - .insert(&conn) - .await - .map_err(|e| *e.current_context()) - }, - )) - .await?; - - Ok::<_, errors::DatabaseError>(()) - }) + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id( + &conn, + user_id.to_owned(), + org_id.to_owned(), + merchant_id.to_owned(), + profile_id.cloned(), + version, + ) .await - .map_err(|error| report!(errors::StorageError::from(report!(error))))?; - - Ok(()) + .map_err(|error| report!(errors::StorageError::from(error))) } } @@ -422,185 +295,6 @@ impl UserRoleInterface for MockDb { .into()) } - async fn update_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let mut user_roles = self.user_roles.lock().await; - - for user_role in user_roles.iter_mut() { - let Some(user_role_merchant_id) = &user_role.merchant_id else { - return Err(errors::StorageError::DatabaseError( - report!(errors::DatabaseError::Others) - .attach_printable("merchant_id not found for user_role"), - ) - .into()); - }; - if user_role.user_id == user_id - && user_role_merchant_id == merchant_id - && user_role.version == version - { - match &update { - storage::UserRoleUpdate::UpdateRole { - role_id, - modified_by, - } => { - user_role.role_id = role_id.to_string(); - user_role.last_modified_by = modified_by.to_string(); - } - storage::UserRoleUpdate::UpdateStatus { - status, - modified_by, - } => { - user_role.status = *status; - user_role.last_modified_by = modified_by.to_string(); - } - }; - return Ok(user_role.clone()); - } - } - - Err(errors::StorageError::ValueNotFound(format!( - "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}" - )) - .into()) - } - - async fn update_user_roles_by_user_id_org_id( - &self, - user_id: &str, - org_id: &id_type::OrganizationId, - update: storage::UserRoleUpdate, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let mut user_roles = self.user_roles.lock().await; - let mut updated_user_roles = Vec::new(); - for user_role in user_roles.iter_mut() { - let Some(user_role_org_id) = &user_role.org_id else { - return Err(errors::StorageError::DatabaseError( - report!(errors::DatabaseError::Others) - .attach_printable("org_id not found for user_role"), - ) - .into()); - }; - if user_role.user_id == user_id - && user_role_org_id == org_id - && user_role.version == version - { - match &update { - storage::UserRoleUpdate::UpdateRole { - role_id, - modified_by, - } => { - user_role.role_id = role_id.to_string(); - user_role.last_modified_by = modified_by.to_string(); - } - storage::UserRoleUpdate::UpdateStatus { - status, - modified_by, - } => { - status.clone_into(&mut user_role.status); - modified_by.clone_into(&mut user_role.last_modified_by); - } - } - updated_user_roles.push(user_role.to_owned()); - } - } - if updated_user_roles.is_empty() { - Err(errors::StorageError::ValueNotFound(format!( - "No user role available for user_id = {user_id} and org_id = {org_id:?}" - )) - .into()) - } else { - Ok(updated_user_roles) - } - } - - async fn transfer_org_ownership_between_users( - &self, - from_user_id: &str, - to_user_id: &str, - org_id: &id_type::OrganizationId, - version: enums::UserRoleVersion, - ) -> CustomResult<(), errors::StorageError> { - let old_org_admin_user_roles = self - .update_user_roles_by_user_id_org_id( - from_user_id, - org_id, - storage::UserRoleUpdate::UpdateRole { - role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), - modified_by: from_user_id.to_string(), - }, - version, - ) - .await?; - - let new_org_admin_user_roles = self - .update_user_roles_by_user_id_org_id( - to_user_id, - org_id, - storage::UserRoleUpdate::UpdateRole { - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - modified_by: from_user_id.to_string(), - }, - version, - ) - .await?; - - let new_org_admin_merchant_ids = new_org_admin_user_roles - .iter() - .map(|user_role| { - user_role.merchant_id.to_owned().ok_or(report!( - errors::StorageError::DatabaseError( - report!(errors::DatabaseError::Others) - .attach_printable("merchant_id not found for user_role"), - ) - )) - }) - .collect::<Result<HashSet<_>, _>>()?; - - let now = common_utils::date_time::now(); - let mut missing_new_user_roles = Vec::new(); - - for old_roles in old_org_admin_user_roles { - let Some(merchant_id) = &old_roles.merchant_id else { - return Err(errors::StorageError::DatabaseError( - report!(errors::DatabaseError::Others) - .attach_printable("merchant id not found for user role"), - ) - .into()); - }; - if !new_org_admin_merchant_ids.contains(merchant_id) { - let new_user_role = storage::UserRoleNew { - user_id: to_user_id.to_string(), - merchant_id: Some(merchant_id.to_owned()), - role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - org_id: Some(org_id.to_owned()), - status: enums::UserStatus::Active, - created_by: from_user_id.to_string(), - last_modified_by: from_user_id.to_string(), - created_at: now, - last_modified: now, - profile_id: None, - entity_id: None, - entity_type: None, - version: enums::UserRoleVersion::V1, - }; - - missing_new_user_roles.push(new_user_role); - } - } - - for user_role in missing_new_user_roles { - self.insert_user_role(user_role).await?; - } - - Ok(()) - } - async fn list_user_roles_by_user_id( &self, user_id: &str, @@ -684,6 +378,60 @@ impl UserRoleInterface for MockDb { .into()) } + async fn update_user_role_by_user_id_and_lineage( + &self, + user_id: &str, + org_id: &id_type::OrganizationId, + merchant_id: &id_type::MerchantId, + profile_id: Option<&String>, + update: storage::UserRoleUpdate, + version: enums::UserRoleVersion, + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let mut user_roles = self.user_roles.lock().await; + + for user_role in user_roles.iter_mut() { + let org_level_check = user_role.org_id.as_ref() == Some(org_id) + && user_role.merchant_id.is_none() + && user_role.profile_id.is_none(); + + let merchant_level_check = user_role.org_id.as_ref() == Some(org_id) + && user_role.merchant_id.as_ref() == Some(merchant_id) + && user_role.profile_id.is_none(); + + let profile_level_check = user_role.org_id.as_ref() == Some(org_id) + && user_role.merchant_id.as_ref() == Some(merchant_id) + && user_role.profile_id.as_ref() == profile_id; + + // Check if the user role matches the conditions and the version matches + if user_role.user_id == user_id + && (org_level_check || merchant_level_check || profile_level_check) + && user_role.version == version + { + match &update { + storage::UserRoleUpdate::UpdateRole { + role_id, + modified_by, + } => { + user_role.role_id = role_id.to_string(); + user_role.last_modified_by = modified_by.to_string(); + } + storage::UserRoleUpdate::UpdateStatus { + status, + modified_by, + } => { + user_role.status = *status; + user_role.last_modified_by = modified_by.to_string(); + } + } + return Ok(user_role.clone()); + } + } + Err( + errors::StorageError::ValueNotFound("Cannot find user role to update".to_string()) + .into(), + ) + } + async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index cb2e1589eed..25e13ba417e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1720,10 +1720,6 @@ impl User { .route(web::put().to(accept_invitation)), ) .service(web::resource("/update_role").route(web::post().to(update_user_role))) - .service( - web::resource("/transfer_ownership") - .route(web::post().to(transfer_org_ownership)), - ) .service(web::resource("/delete").route(web::delete().to(delete_user_role))), ); diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index bce0e6da147..526722af98c 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -186,25 +186,6 @@ pub async fn update_user_role( .await } -pub async fn transfer_org_ownership( - state: web::Data<AppState>, - req: HttpRequest, - json_payload: web::Json<user_role_api::TransferOrgOwnershipRequest>, -) -> HttpResponse { - let flow = Flow::TransferOrgOwnership; - let payload = json_payload.into_inner(); - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload, - user_role_core::transfer_org_ownership, - &auth::JWTAuth(Permission::UsersWrite), - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn accept_invitation( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 4fcc03b1904..7aebbe1bbcf 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -3,9 +3,13 @@ use std::collections::HashSet; use api_models::user_role as user_role_api; use common_enums::PermissionGroup; use common_utils::id_type; -use diesel_models::user_role::UserRole; -use error_stack::{report, ResultExt}; +use diesel_models::{ + enums::UserRoleVersion, + user_role::{UserRole, UserRoleUpdate}, +}; +use error_stack::{report, Report, ResultExt}; use router_env::logger; +use storage_impl::errors::StorageError; use crate::{ consts, @@ -168,7 +172,53 @@ pub async fn get_multiple_role_info_for_user_roles( .await .to_not_found_response(UserErrors::InternalServerError) .attach_printable("Role for user role doesn't exist")?; - Ok::<_, error_stack::Report<UserErrors>>(role) + Ok::<_, Report<UserErrors>>(role) })) .await } + +pub async fn update_v1_and_v2_user_roles_in_db( + state: &SessionState, + user_id: &str, + org_id: &id_type::OrganizationId, + merchant_id: &id_type::MerchantId, + profile_id: Option<&String>, + update: UserRoleUpdate, +) -> ( + Result<UserRole, Report<StorageError>>, + Result<UserRole, Report<StorageError>>, +) { + let updated_v1_role = state + .store + .update_user_role_by_user_id_and_lineage( + user_id, + org_id, + merchant_id, + profile_id, + update.clone(), + UserRoleVersion::V1, + ) + .await + .map_err(|e| { + logger::error!("Error updating user_role {e:?}"); + e + }); + + let updated_v2_role = state + .store + .update_user_role_by_user_id_and_lineage( + user_id, + org_id, + merchant_id, + profile_id, + update, + UserRoleVersion::V2, + ) + .await + .map_err(|e| { + logger::error!("Error updating user_role {e:?}"); + e + }); + + (updated_v1_role, updated_v2_role) +}
feat
Add update by lineage DB function (#5651)
11aeff53bf209634fa84988f65974447139a2548
2024-01-05 12:50:19
github-actions
chore(version): v1.106.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 30b7957272c..7f7a2ced4db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.106.1 (2024-01-05) + +### Bug Fixes + +- **connector:** [iatapay] change refund amount ([#3244](https://github.com/juspay/hyperswitch/pull/3244)) ([`e79604b`](https://github.com/juspay/hyperswitch/commit/e79604bd4681a69802f3c3169dd94424e3688e42)) + +**Full Changelog:** [`v1.106.0...v1.106.1`](https://github.com/juspay/hyperswitch/compare/v1.106.0...v1.106.1) + +- - - + + ## 1.106.0 (2024-01-04) ### Features
chore
v1.106.1
d680eb2b49f85795daafdda9caa0fd3fe6db8108
2023-10-26 11:37:58
Sanchith Hegde
build(docker): copy over `.gitignore` as `.dockerignore` (#2691)
false
diff --git a/.dockerignore b/.dockerignore index 35515ecf138..62804a712fa 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,17 +1,267 @@ -target -openapi -monitoring -logs -docs -connector-template -.cargo -.vscode -postman -kubernetes -*Dockerfile +# Created by https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows + +### CLion ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### CLion Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### direnv ### +.direnv +.envrc + +### dotenv ### .env -.dockerignore -.gitignore -Makefile -*.sh -Jenkinsfile \ No newline at end of file + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +!Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope +.vscode/*.code-snippets + +# Ignore code-workspaces +*.code-workspace + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows + +# hyperswitch Project specific excludes +# code coverage report +*.profraw +html/ +coverage.json +# other +logs/ +**/tmp +**/*.log +**/*.log.* +monitoring/*.tmp/ +config/sandbox.toml +config/production.toml +!loadtest/.env +loadtest/*.tmp/ + +# Nix output +result* + +.idea/ + +# node_modules +node_modules/ + +**/connector_auth.toml +**/sample_auth.toml +**/auth.toml
build
copy over `.gitignore` as `.dockerignore` (#2691)
afa803e0f9711f83b31ce53a59e867517a885963
2024-10-17 15:50:47
Sai Harsha Vardhan
feat(router): add payments create-intent flow for v2 (#6193)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e16a206b118..1f296a1081d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -13446,7 +13446,7 @@ "payment_link_config": { "allOf": [ { - "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig" + "$ref": "#/components/schemas/PaymentLinkConfigRequest" } ], "nullable": true @@ -13486,6 +13486,7 @@ "PaymentsCreateIntentResponse": { "type": "object", "required": [ + "id", "amount_details", "client_secret", "capture_method", @@ -13495,9 +13496,14 @@ "apply_mit_exemption", "payment_link_enabled", "request_incremental_authorization", + "expires_on", "request_external_three_ds_authentication" ], "properties": { + "id": { + "type": "string", + "description": "Global Payment Id for the payment" + }, "amount_details": { "$ref": "#/components/schemas/AmountDetails" }, @@ -13626,7 +13632,7 @@ "payment_link_config": { "allOf": [ { - "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig" + "$ref": "#/components/schemas/PaymentLinkConfigRequest" } ], "nullable": true @@ -13634,13 +13640,10 @@ "request_incremental_authorization": { "$ref": "#/components/schemas/RequestIncrementalAuthorization" }, - "session_expiry": { - "type": "integer", - "format": "int32", - "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config\n(900) for 15 mins", - "example": 900, - "nullable": true, - "minimum": 0 + "expires_on": { + "type": "string", + "format": "date-time", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds" }, "frm_metadata": { "type": "object", diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 1f66fb521e4..7bbff94d453 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -1,5 +1,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(feature = "v2")] +use super::PaymentsCreateIntentRequest; +#[cfg(feature = "v2")] +use super::PaymentsCreateIntentResponse; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") @@ -29,6 +33,8 @@ use crate::{ PaymentsStartRequest, RedirectionResponse, }, }; + +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.resource_id { @@ -40,6 +46,7 @@ impl ApiEventMetric for PaymentsRetrieveRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsStartRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -48,6 +55,7 @@ impl ApiEventMetric for PaymentsStartRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -56,6 +64,7 @@ impl ApiEventMetric for PaymentsCaptureRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -64,6 +73,7 @@ impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -72,6 +82,7 @@ impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -80,6 +91,7 @@ impl ApiEventMetric for PaymentsPostSessionTokensRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -88,8 +100,10 @@ impl ApiEventMetric for PaymentsPostSessionTokensResponse { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {} +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -98,6 +112,7 @@ impl ApiEventMetric for PaymentsCancelRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsApproveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -106,6 +121,7 @@ impl ApiEventMetric for PaymentsApproveRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRejectRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -114,6 +130,7 @@ impl ApiEventMetric for PaymentsRejectRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.payment_id { @@ -125,6 +142,23 @@ impl ApiEventMetric for PaymentsRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentsCreateIntentRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentsCreateIntentResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.id.clone(), + }) + } +} + +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -262,6 +296,7 @@ impl ApiEventMetric for PaymentsAggregateResponse { impl ApiEventMetric for RedirectionResponse {} +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -270,8 +305,10 @@ impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationResponse {} +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -280,8 +317,10 @@ impl ApiEventMetric for PaymentsExternalAuthenticationRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for ExtendedCardInfoResponse {} +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -290,6 +329,7 @@ impl ApiEventMetric for PaymentsManualUpdateRequest { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { @@ -298,6 +338,7 @@ impl ApiEventMetric for PaymentsManualUpdateResponse { } } +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentsSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 674a19f3ef8..9b4bd78b09e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5,6 +5,8 @@ use std::{ }; pub mod additional_info; use cards::CardNumber; +#[cfg(feature = "v2")] +use common_utils::id_type::GlobalPaymentId; use common_utils::{ consts::default_payments_list_limit, crypto, @@ -162,7 +164,7 @@ pub struct PaymentsCreateIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] - pub return_url: Option<Url>, + pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, @@ -203,8 +205,8 @@ pub struct PaymentsCreateIntentRequest { pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment - #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] - pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, + #[schema(value_type = Option<PaymentLinkConfigRequest>)] + pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] @@ -225,16 +227,81 @@ pub struct PaymentsCreateIntentRequest { Option<common_enums::External3dsAuthenticationRequest>, } +#[cfg(feature = "v2")] +impl PaymentsCreateIntentRequest { + pub fn get_feature_metadata_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<pii::SecretSerdeValue>, + common_utils::errors::ParsingError, + > { + Ok(self + .feature_metadata + .as_ref() + .map(Encode::encode_to_value) + .transpose()? + .map(Secret::new)) + } + + pub fn get_connector_metadata_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<pii::SecretSerdeValue>, + common_utils::errors::ParsingError, + > { + Ok(self + .connector_metadata + .as_ref() + .map(Encode::encode_to_value) + .transpose()? + .map(Secret::new)) + } + + pub fn get_allowed_payment_method_types_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<pii::SecretSerdeValue>, + common_utils::errors::ParsingError, + > { + Ok(self + .allowed_payment_method_types + .as_ref() + .map(Encode::encode_to_value) + .transpose()? + .map(Secret::new)) + } + + pub fn get_order_details_as_value( + &self, + ) -> common_utils::errors::CustomResult< + Option<Vec<pii::SecretSerdeValue>>, + common_utils::errors::ParsingError, + > { + self.order_details + .as_ref() + .map(|od| { + od.iter() + .map(|order| order.encode_to_value().map(Secret::new)) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + } +} + #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentResponse { + /// Global Payment Id for the payment + #[schema(value_type = String)] + pub id: GlobalPaymentId, + /// The amount details for the payment pub amount_details: AmountDetails, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] - pub client_secret: Secret<String>, + pub client_secret: common_utils::types::ClientSecret, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. @@ -257,9 +324,11 @@ pub struct PaymentsCreateIntentResponse { pub authentication_type: api_enums::AuthenticationType, /// The billing details of the payment. This address will be used for invoicing. + #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment + #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer @@ -276,7 +345,7 @@ pub struct PaymentsCreateIntentResponse { /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] - pub return_url: Option<Url>, + pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, @@ -300,34 +369,35 @@ pub struct PaymentsCreateIntentResponse { /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] - pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, + pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. - pub connector_metadata: Option<ConnectorMetadata>, + #[schema(value_type = Option<ConnectorMetadata>)] + pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. - pub feature_metadata: Option<FeatureMetadata>, + #[schema(value_type = Option<FeatureMetadata>)] + pub feature_metadata: Option<pii::SecretSerdeValue>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment - #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] - pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, + #[schema(value_type = Option<PaymentLinkConfigRequest>)] + pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, - ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config - ///(900) for 15 mins - #[schema(example = 900)] - pub session_expiry: Option<u32>, + ///Will be used to expire client secret after certain amount of time to be supplied in seconds + #[serde(with = "common_utils::custom_serde::iso8601")] + pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] @@ -366,6 +436,58 @@ pub struct AmountDetails { tax_on_surcharge: Option<MinorUnit>, } +#[cfg(feature = "v2")] +pub struct AmountDetailsSetter { + pub order_amount: Amount, + pub currency: common_enums::Currency, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, + pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, + pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, + pub surcharge_amount: Option<MinorUnit>, + pub tax_on_surcharge: Option<MinorUnit>, +} + +#[cfg(feature = "v2")] +impl AmountDetails { + pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { + Self { + order_amount: amount_details_setter.order_amount, + currency: amount_details_setter.currency, + shipping_cost: amount_details_setter.shipping_cost, + order_tax_amount: amount_details_setter.order_tax_amount, + skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, + skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, + surcharge_amount: amount_details_setter.surcharge_amount, + tax_on_surcharge: amount_details_setter.tax_on_surcharge, + } + } + pub fn order_amount(&self) -> Amount { + self.order_amount + } + pub fn currency(&self) -> common_enums::Currency { + self.currency + } + pub fn shipping_cost(&self) -> Option<MinorUnit> { + self.shipping_cost + } + pub fn order_tax_amount(&self) -> Option<MinorUnit> { + self.order_tax_amount + } + pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { + self.skip_external_tax_calculation.clone() + } + pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { + self.skip_surcharge_calculation.clone() + } + pub fn surcharge_amount(&self) -> Option<MinorUnit> { + self.surcharge_amount + } + pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { + self.tax_on_surcharge + } +} + #[derive( Default, Debug, @@ -3489,6 +3611,8 @@ pub struct Address { pub email: Option<Email>, } +impl masking::SerializableSecret for Address {} + impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { @@ -4808,6 +4932,8 @@ pub struct OrderDetailsWithAmount { pub product_tax_code: Option<String>, } +impl masking::SerializableSecret for OrderDetailsWithAmount {} + #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ProductType { diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index fdc9670045e..dcdb4c760b1 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -default = ["v1"] +default = [] keymanager = ["dep:router_env"] keymanager_mtls = ["reqwest/rustls-tls"] encryption_service = ["dep:router_env"] diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index 8b8707d9b99..c7f1c286c59 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -485,6 +485,24 @@ impl<T: Clone> Encryptable<T> { pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } + + /// + /// Deserialize inner value and return new Encryptable object + /// + pub fn deserialize_inner_value<U, F>( + self, + f: F, + ) -> CustomResult<Encryptable<U>, errors::ParsingError> + where + F: FnOnce(T) -> CustomResult<U, errors::ParsingError>, + U: Clone, + { + // Option::map(self, f) + let inner = self.inner; + let encrypted = self.encrypted; + let inner = f(inner)?; + Ok(Encryptable { inner, encrypted }) + } } impl<T: Clone> Deref for Encryptable<Secret<T>> { diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 2b1571617e8..1b03f8f19f2 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -15,9 +15,14 @@ pub enum ApiEventsType { Payout { payout_id: String, }, + #[cfg(feature = "v1")] Payment { payment_id: id_type::PaymentId, }, + #[cfg(feature = "v2")] + Payment { + payment_id: id_type::GlobalPaymentId, + }, Refund { payment_id: Option<id_type::PaymentId>, refund_id: String, @@ -82,6 +87,7 @@ pub enum ApiEventsType { impl ApiEventMetric for serde_json::Value {} impl ApiEventMetric for () {} +#[cfg(feature = "v1")] impl ApiEventMetric for id_type::PaymentId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs index edc7e3fb960..a404c7bc9c4 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -1,4 +1,6 @@ -use crate::errors; +use error_stack::ResultExt; + +use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; /// A global id that can be used to identify a payment #[derive( @@ -22,6 +24,17 @@ impl GlobalPaymentId { pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } + + /// Generate a new GlobalPaymentId from a cell id + pub fn generate(cell_id: crate::id_type::CellId) -> Self { + let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Payment); + Self(global_id) + } + + /// Generate a new ClientId from self + pub fn generate_client_secret(&self) -> types::ClientSecret { + types::ClientSecret::new(self.clone(), generate_time_ordered_id_without_prefix()) + } } // TODO: refactor the macro to include this id use case as well diff --git a/crates/common_utils/src/id_type/payment.rs b/crates/common_utils/src/id_type/payment.rs index d82a697b082..60bc9968f31 100644 --- a/crates/common_utils/src/id_type/payment.rs +++ b/crates/common_utils/src/id_type/payment.rs @@ -75,6 +75,10 @@ crate::impl_id_type_methods!(PaymentReferenceId, "payment_reference_id"); crate::impl_debug_id_type!(PaymentReferenceId); crate::impl_try_from_cow_str_id_type!(PaymentReferenceId, "payment_reference_id"); +// Database related implementations so that this field can be used directly in the database tables +crate::impl_queryable_id_type!(PaymentReferenceId); +crate::impl_to_sql_from_sql_id_type!(PaymentReferenceId); + #[cfg(feature = "metrics")] /// This is implemented so that we can use payment id directly as attribute in metrics impl From<PaymentId> for router_env::opentelemetry::Value { diff --git a/crates/common_utils/src/id_type/profile.rs b/crates/common_utils/src/id_type/profile.rs index e9d90e7bba1..a73cdfdd539 100644 --- a/crates/common_utils/src/id_type/profile.rs +++ b/crates/common_utils/src/id_type/profile.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + crate::id_type!( ProfileId, "A type for profile_id that can be used for business profile ids" @@ -20,3 +22,12 @@ impl crate::events::ApiEventMetric for ProfileId { }) } } + +impl FromStr for ProfileId { + type Err = error_stack::Report<crate::errors::ValidationError>; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + let cow_string = std::borrow::Cow::Owned(s.to_string()); + Self::try_from(cow_string) + } +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index ecffa259bc3..923bdf89c02 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -264,6 +264,12 @@ pub fn generate_time_ordered_id(prefix: &str) -> String { format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple()) } +/// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix +#[inline] +pub fn generate_time_ordered_id_without_prefix() -> String { + uuid::Uuid::now_v7().as_simple().to_string() +} + #[allow(missing_docs)] pub trait DbConnectionParams { fn get_username(&self) -> &str; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 0cad88bfd4f..e11ddbf7a3e 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -633,6 +633,7 @@ mod client_secret_type { use std::fmt; use masking::PeekInterface; + use router_env::logger; use super::*; use crate::id_type; @@ -656,6 +657,14 @@ mod client_secret_type { self.secret.peek() ) } + + /// Create a new client secret + pub(crate) fn new(payment_id: id_type::GlobalPaymentId, secret: String) -> Self { + Self { + payment_id, + secret: masking::Secret::new(secret), + } + } } impl<'de> Deserialize<'de> for ClientSecret { @@ -730,7 +739,23 @@ mod client_secret_type { { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let string_repr = String::from_sql(value)?; - Ok(serde_json::from_str(&string_repr)?) + let (payment_id, secret) = + string_repr + .rsplit_once("_secret_") + .ok_or(ParsingError::EncodeError( + "Expected a string in the format '{payment_id}_secret_{secret}'", + ))?; + + let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) + .map_err(|err| { + logger::error!(global_payment_id_error=?err); + ParsingError::EncodeError("Error while constructing GlobalPaymentId") + })?; + + Ok(Self { + payment_id, + secret: masking::Secret::new(secret.to_owned()), + }) } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 23d1a0f1ac8..f53594075af 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -31,7 +31,7 @@ pub struct PaymentIntent { pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, - pub active_attempt_id: String, + pub active_attempt_id: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, @@ -44,7 +44,7 @@ pub struct PaymentIntent { pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, - pub session_expiry: Option<PrimitiveDateTime>, + pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, @@ -52,7 +52,7 @@ pub struct PaymentIntent { pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, - pub merchant_reference_id: Option<common_utils::id_type::PaymentId>, + pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, @@ -228,7 +228,7 @@ pub struct PaymentIntentNew { pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, - pub active_attempt_id: String, + pub active_attempt_id: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, @@ -241,8 +241,8 @@ pub struct PaymentIntentNew { pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, - #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub session_expiry: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, @@ -250,7 +250,7 @@ pub struct PaymentIntentNew { pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, - pub merchant_reference_id: Option<common_utils::id_type::PaymentId>, + pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 53f568f18c4..9d1a47e4e0a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -845,7 +845,7 @@ diesel::table! { #[max_length = 128] client_secret -> Varchar, #[max_length = 64] - active_attempt_id -> Varchar, + active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, @@ -860,7 +860,7 @@ diesel::table! { surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, authorization_count -> Nullable<Int4>, - session_expiry -> Nullable<Timestamp>, + session_expiry -> Timestamp, request_external_three_ds_authentication -> Nullable<Bool>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index c99fbd89cd5..4803514617f 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -54,3 +54,109 @@ impl<T: ForeignIDRef> RemoteStorageObject<T> { } } } + +use std::fmt::Debug; + +pub trait ApiModelToDieselModelConvertor<F> { + /// Convert from a foreign type to the current type + fn convert_from(from: F) -> Self; +} + +#[cfg(feature = "v2")] +impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> + for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments +{ + fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self { + Self { + theme: item.theme, + logo: item.logo, + seller_name: item.seller_name, + sdk_layout: item.sdk_layout, + display_sdk_only: item.display_sdk_only, + enabled_saved_payment_method: item.enabled_saved_payment_method, + transaction_details: item.transaction_details.map(|transaction_details| { + transaction_details + .into_iter() + .map(|transaction_detail| { + diesel_models::PaymentLinkTransactionDetails::convert_from( + transaction_detail, + ) + }) + .collect() + }), + } + } +} + +#[cfg(feature = "v2")] +impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails> + for diesel_models::PaymentLinkTransactionDetails +{ + fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { + Self { + key: from.key, + value: from.value, + ui_configuration: from + .ui_configuration + .map(diesel_models::TransactionDetailsUiConfiguration::convert_from), + } + } +} + +#[cfg(feature = "v2")] +impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration> + for diesel_models::TransactionDetailsUiConfiguration +{ + fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { + Self { + position: from.position, + is_key_bold: from.is_key_bold, + is_value_bold: from.is_value_bold, + } + } +} + +#[cfg(feature = "v2")] +impl From<api_models::payments::AmountDetails> for payments::AmountDetails { + fn from(amount_details: api_models::payments::AmountDetails) -> Self { + Self { + order_amount: amount_details.order_amount().into(), + currency: amount_details.currency(), + shipping_cost: amount_details.shipping_cost(), + tax_details: Some(diesel_models::TaxDetails { + default: amount_details + .order_tax_amount() + .map(|order_tax_amount| diesel_models::DefaultTax { order_tax_amount }), + payment_method_type: None, + }), + skip_external_tax_calculation: payments::TaxCalculationOverride::from( + amount_details.skip_external_tax_calculation(), + ), + skip_surcharge_calculation: payments::SurchargeCalculationOverride::from( + amount_details.skip_surcharge_calculation(), + ), + surcharge_amount: amount_details.surcharge_amount(), + tax_on_surcharge: amount_details.tax_on_surcharge(), + } + } +} + +#[cfg(feature = "v2")] +impl From<common_enums::SurchargeCalculationOverride> for payments::SurchargeCalculationOverride { + fn from(surcharge_calculation_override: common_enums::SurchargeCalculationOverride) -> Self { + match surcharge_calculation_override { + common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate, + common_enums::SurchargeCalculationOverride::Skip => Self::Skip, + } + } +} + +#[cfg(feature = "v2")] +impl From<common_enums::TaxCalculationOverride> for payments::TaxCalculationOverride { + fn from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self { + match tax_calculation_override { + common_enums::TaxCalculationOverride::Calculate => Self::Calculate, + common_enums::TaxCalculationOverride::Skip => Self::Skip, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 2d7d49e81c7..4c8cb9c38ea 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -1,8 +1,14 @@ #[cfg(feature = "v2")] use std::marker::PhantomData; +#[cfg(feature = "v2")] +use api_models::payments::Address; +#[cfg(feature = "v2")] +use api_models::payments::OrderDetailsWithAmount; use common_utils::{self, crypto::Encryptable, id_type, pii, types::MinorUnit}; use diesel_models::payment_intent::TaxDetails; +#[cfg(feature = "v2")] +use error_stack::ResultExt; use masking::Secret; use time::PrimitiveDateTime; @@ -13,6 +19,10 @@ use common_enums as storage_enums; use self::payment_attempt::PaymentAttempt; use crate::RemoteStorageObject; +#[cfg(feature = "v2")] +use crate::{business_profile, merchant_account}; +#[cfg(feature = "v2")] +use crate::{errors, ApiModelToDieselModelConvertor}; #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] @@ -200,13 +210,13 @@ pub struct PaymentIntent { pub modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, + pub setup_future_usage: storage_enums::FutureUsage, /// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis. pub client_secret: common_utils::types::ClientSecret, /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent. - pub active_attempt: RemoteStorageObject<PaymentAttempt>, + pub active_attempt: Option<RemoteStorageObject<PaymentAttempt>>, /// The order details for the payment. - pub order_details: Option<Vec<pii::SecretSerdeValue>>, + pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// This is the list of payment method types that are allowed for the payment intent. /// This field allows the merchant to restrict the payment methods that can be used for the payment intent. pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, @@ -225,12 +235,12 @@ pub struct PaymentIntent { /// Denotes the last instance which updated the payment pub updated_by: String, /// Denotes whether merchant requested for incremental authorization to be enabled for this payment. - pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, + pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization, /// Denotes the number of authorizations that have been made for the payment. pub authorization_count: Option<i32>, /// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire. - #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub session_expiry: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub session_expiry: PrimitiveDateTime, /// Denotes whether merchant requested for 3ds authentication to be enabled for this payment. pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, /// Metadata related to fraud and risk management @@ -238,15 +248,15 @@ pub struct PaymentIntent { /// The details of the customer in a denormalized form. Only a subset of fields are stored. pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. - pub merchant_reference_id: Option<id_type::PaymentId>, + pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The billing address for the order in a denormalized form. - pub billing_address: Option<Encryptable<Secret<serde_json::Value>>>, + pub billing_address: Option<Encryptable<Secret<Address>>>, /// The shipping address for the order in a denormalized form. - pub shipping_address: Option<Encryptable<Secret<serde_json::Value>>>, + pub shipping_address: Option<Encryptable<Secret<Address>>>, /// Capture method for the payment - pub capture_method: Option<storage_enums::CaptureMethod>, + pub capture_method: storage_enums::CaptureMethod, /// Authentication type that is requested by the merchant for this payment. - pub authentication_type: Option<common_enums::AuthenticationType>, + pub authentication_type: common_enums::AuthenticationType, /// This contains the pre routing results that are done when routing is done during listing the payment methods. pub prerouting_algorithm: Option<serde_json::Value>, /// The organization id for the payment. This is derived from the merchant account @@ -263,6 +273,117 @@ pub struct PaymentIntent { pub routing_algorithm_id: Option<id_type::RoutingId>, } +#[cfg(feature = "v2")] +impl PaymentIntent { + fn get_request_incremental_authorization_value( + request: &api_models::payments::PaymentsCreateIntentRequest, + ) -> common_utils::errors::CustomResult< + common_enums::RequestIncrementalAuthorization, + errors::api_error_response::ApiErrorResponse, + > { + request.request_incremental_authorization + .map(|request_incremental_authorization| { + if request_incremental_authorization == common_enums::RequestIncrementalAuthorization::True { + if request.capture_method == Some(common_enums::CaptureMethod::Automatic) { + Err(errors::api_error_response::ApiErrorResponse::InvalidRequestData { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })? + } + Ok(common_enums::RequestIncrementalAuthorization::True) + } else { + Ok(common_enums::RequestIncrementalAuthorization::False) + } + }) + .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) + } + pub async fn create_domain_model_from_request( + payment_id: &id_type::GlobalPaymentId, + merchant_account: &merchant_account::MerchantAccount, + profile: &business_profile::Profile, + request: api_models::payments::PaymentsCreateIntentRequest, + billing_address: Option<Encryptable<Secret<Address>>>, + shipping_address: Option<Encryptable<Secret<Address>>>, + ) -> common_utils::errors::CustomResult<Self, errors::api_error_response::ApiErrorResponse> + { + let allowed_payment_method_types = request + .get_allowed_payment_method_types_as_value() + .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting allowed payment method types as value")?; + let connector_metadata = request + .get_connector_metadata_as_value() + .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting connector metadata as value")?; + let feature_metadata = request + .get_feature_metadata_as_value() + .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting feature metadata as value")?; + let request_incremental_authorization = + Self::get_request_incremental_authorization_value(&request)?; + let session_expiry = + common_utils::date_time::now().saturating_add(time::Duration::seconds( + request.session_expiry.map(i64::from).unwrap_or( + profile + .session_expiry + .unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY), + ), + )); + let client_secret = payment_id.generate_client_secret(); + let order_details = request + .order_details + .map(|order_details| order_details.into_iter().map(Secret::new).collect()); + Ok(Self { + id: payment_id.clone(), + merchant_id: merchant_account.get_id().clone(), + // Intent status would be RequiresPaymentMethod because we are creating a new payment intent + status: common_enums::IntentStatus::RequiresPaymentMethod, + amount_details: AmountDetails::from(request.amount_details), + amount_captured: None, + customer_id: request.customer_id, + description: request.description, + return_url: request.return_url, + metadata: request.metadata, + statement_descriptor: request.statement_descriptor, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + last_synced: None, + setup_future_usage: request.setup_future_usage.unwrap_or_default(), + client_secret, + active_attempt: None, + order_details, + allowed_payment_method_types, + connector_metadata, + feature_metadata, + // Attempt count is 0 in create intent as no attempt is made yet + attempt_count: 0, + profile_id: profile.get_id().clone(), + payment_link_id: None, + frm_merchant_decision: None, + updated_by: merchant_account.storage_scheme.to_string(), + request_incremental_authorization, + // Authorization count is 0 in create intent as no authorization is made yet + authorization_count: Some(0), + session_expiry, + request_external_three_ds_authentication: request + .request_external_three_ds_authentication + .unwrap_or_default(), + frm_metadata: request.frm_metadata, + customer_details: None, + merchant_reference_id: request.merchant_reference_id, + billing_address, + shipping_address, + capture_method: request.capture_method.unwrap_or_default(), + authentication_type: request.authentication_type.unwrap_or_default(), + prerouting_algorithm: None, + organization_id: merchant_account.organization_id.clone(), + enable_payment_link: request.payment_link_enabled.unwrap_or_default(), + apply_mit_exemption: request.apply_mit_exemption.unwrap_or_default(), + customer_present: request.customer_present.unwrap_or_default(), + payment_link_config: request + .payment_link_config + .map(ApiModelToDieselModelConvertor::convert_from), + routing_algorithm_id: request.routing_algorithm_id, + }) + } +} + #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentIntentData<F> diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index be2b3547110..ebd630beb62 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,4 +1,6 @@ use common_enums as storage_enums; +#[cfg(feature = "v2")] +use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, crypto::{self, Encryptable}, @@ -16,6 +18,8 @@ use diesel_models::{ PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; use error_stack::ResultExt; +#[cfg(feature = "v2")] +use masking::ExposeInterface; use masking::{Deserialize, PeekInterface, Secret}; use rustc_hash::FxHashMap; use serde::Serialize; @@ -1524,10 +1528,20 @@ impl behaviour::Conversion for PaymentIntent { created_at, modified_at, last_synced, - setup_future_usage, + setup_future_usage: Some(setup_future_usage), client_secret, - active_attempt_id: active_attempt.get_id(), - order_details, + active_attempt_id: active_attempt.map(|attempt| attempt.get_id()), + order_details: order_details + .map(|order_details| { + order_details + .into_iter() + .map(|order_detail| order_detail.encode_to_value().map(Secret::new)) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + .change_context(ValidationError::InvalidValue { + message: "invalid value found for order_details".to_string(), + })?, allowed_payment_method_types, connector_metadata, feature_metadata, @@ -1537,7 +1551,7 @@ impl behaviour::Conversion for PaymentIntent { payment_link_id, updated_by, - request_incremental_authorization, + request_incremental_authorization: Some(request_incremental_authorization), authorization_count, session_expiry, request_external_three_ds_authentication: Some( @@ -1547,9 +1561,9 @@ impl behaviour::Conversion for PaymentIntent { customer_details: customer_details.map(Encryption::from), billing_address: billing_address.map(Encryption::from), shipping_address: shipping_address.map(Encryption::from), - capture_method, + capture_method: Some(capture_method), id, - authentication_type, + authentication_type: Some(authentication_type), prerouting_algorithm, merchant_reference_id, surcharge_amount: amount_details.surcharge_amount, @@ -1608,6 +1622,23 @@ impl behaviour::Conversion for PaymentIntent { storage_model.surcharge_applicable, ), }; + let billing_address = data + .billing + .map(|billing| { + billing.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Address")?; + + let shipping_address = data + .shipping + .map(|shipping| { + shipping.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Address")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { merchant_id: storage_model.merchant_id, @@ -1622,10 +1653,23 @@ impl behaviour::Conversion for PaymentIntent { created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, - setup_future_usage: storage_model.setup_future_usage, + setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), client_secret: storage_model.client_secret, - active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), - order_details: storage_model.order_details, + active_attempt: storage_model + .active_attempt_id + .map(RemoteStorageObject::ForeignID), + order_details: storage_model + .order_details + .map(|order_details| { + order_details + .into_iter() + .map(|order_detail| { + order_detail.expose().parse_value("OrderDetailsWithAmount") + }) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed)?, allowed_payment_method_types: storage_model.allowed_payment_method_types, connector_metadata: storage_model.connector_metadata, feature_metadata: storage_model.feature_metadata, @@ -1634,7 +1678,9 @@ impl behaviour::Conversion for PaymentIntent { frm_merchant_decision: storage_model.frm_merchant_decision, payment_link_id: storage_model.payment_link_id, updated_by: storage_model.updated_by, - request_incremental_authorization: storage_model.request_incremental_authorization, + request_incremental_authorization: storage_model + .request_incremental_authorization + .unwrap_or_default(), authorization_count: storage_model.authorization_count, session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: @@ -1643,13 +1689,13 @@ impl behaviour::Conversion for PaymentIntent { ), frm_metadata: storage_model.frm_metadata, customer_details: data.customer_details, - billing_address: data.billing, - shipping_address: data.shipping, - capture_method: storage_model.capture_method, + billing_address, + shipping_address, + capture_method: storage_model.capture_method.unwrap_or_default(), id: storage_model.id, merchant_reference_id: storage_model.merchant_reference_id, organization_id: storage_model.organization_id, - authentication_type: storage_model.authentication_type, + authentication_type: storage_model.authentication_type.unwrap_or_default(), prerouting_algorithm: storage_model.prerouting_algorithm, enable_payment_link: common_enums::EnablePaymentLinkRequest::from( storage_model.enable_payment_link, @@ -1689,10 +1735,21 @@ impl behaviour::Conversion for PaymentIntent { created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, - setup_future_usage: self.setup_future_usage, + setup_future_usage: Some(self.setup_future_usage), client_secret: self.client_secret, - active_attempt_id: self.active_attempt.get_id(), - order_details: self.order_details, + active_attempt_id: self.active_attempt.map(|attempt| attempt.get_id()), + order_details: self + .order_details + .map(|order_details| { + order_details + .into_iter() + .map(|order_detail| order_detail.encode_to_value().map(Secret::new)) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + .change_context(ValidationError::InvalidValue { + message: "Invalid value found for ".to_string(), + })?, allowed_payment_method_types: self.allowed_payment_method_types, connector_metadata: self.connector_metadata, feature_metadata: self.feature_metadata, @@ -1702,7 +1759,7 @@ impl behaviour::Conversion for PaymentIntent { payment_link_id: self.payment_link_id, updated_by: self.updated_by, - request_incremental_authorization: self.request_incremental_authorization, + request_incremental_authorization: Some(self.request_incremental_authorization), authorization_count: self.authorization_count, session_expiry: self.session_expiry, request_external_three_ds_authentication: Some( @@ -1712,10 +1769,10 @@ impl behaviour::Conversion for PaymentIntent { customer_details: self.customer_details.map(Encryption::from), billing_address: self.billing_address.map(Encryption::from), shipping_address: self.shipping_address.map(Encryption::from), - capture_method: self.capture_method, + capture_method: Some(self.capture_method), id: self.id, merchant_reference_id: self.merchant_reference_id, - authentication_type: self.authentication_type, + authentication_type: Some(self.authentication_type), prerouting_algorithm: self.prerouting_algorithm, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, 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 10153fc05ec..602c184139f 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -56,5 +56,8 @@ pub struct CalculateTax; #[derive(Debug, Clone)] pub struct SdkSessionUpdate; +#[derive(Debug, Clone)] +pub struct CreateIntent; + #[derive(Debug, Clone)] pub struct PostSessionTokens; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index d599a2caa74..704387ad461 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -526,14 +526,6 @@ pub struct SurchargeDetails { } impl SurchargeDetails { - pub fn is_request_surcharge_matching( - &self, - request_surcharge_details: RequestSurchargeDetails, - ) -> bool { - request_surcharge_details.surcharge_amount == self.surcharge_amount - && request_surcharge_details.tax_amount.unwrap_or_default() - == self.tax_on_surcharge_amount - } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_on_surcharge_amount } diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 6aae926011a..dac22071c36 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -12,7 +12,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order # First party crates api_models = { version = "0.1.0", path = "../api_models", features = ["frm", "payouts", "openapi"] } -common_utils = { version = "0.1.0", path = "../common_utils" } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["logs"] } router_env = { version = "0.1.0", path = "../router_env" } [features] diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 7cecf49496b..190e25d71c9 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -54,7 +54,7 @@ pub async fn customer_create( state.into_inner(), &req, create_cust_req, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { customers::create_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -92,7 +92,7 @@ pub async fn customer_retrieve( state.into_inner(), &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { customers::retrieve_customer(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -142,7 +142,7 @@ pub async fn customer_update( state.into_inner(), &req, cust_update_req, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { customers::update_customer( state, auth.merchant_account, @@ -225,7 +225,7 @@ pub async fn list_customer_payment_method_api( state.into_inner(), &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index ec3dd9cc953..901ca3c11c2 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -71,7 +71,7 @@ pub async fn payment_intents_create( state.into_inner(), &req, create_payment_req, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, @@ -452,7 +452,7 @@ pub async fn payment_intents_capture( state.into_inner(), &req, payload, - |state, auth, payload, req_state| { + |state, auth: auth::AuthenticationData, payload, req_state| { payments::payments_core::< api_types::Capture, api_types::PaymentsResponse, @@ -581,7 +581,7 @@ pub async fn payment_intent_list( state.into_inner(), &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payments::list_payments(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 09585cd9c3a..63141f7311c 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -49,7 +49,7 @@ pub async fn refund_create( state.into_inner(), &req, create_refund_req, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { refunds::refund_create_core(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -93,7 +93,7 @@ pub async fn refund_retrieve_with_gateway_creds( state.into_inner(), &req, refund_request, - |state, auth, refund_request, _| { + |state, auth: auth::AuthenticationData, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, @@ -136,7 +136,7 @@ pub async fn refund_retrieve( state.into_inner(), &req, refund_request, - |state, auth, refund_request, _| { + |state, auth: auth::AuthenticationData, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, @@ -177,7 +177,9 @@ pub async fn refund_update( state.into_inner(), &req, create_refund_update_req, - |state, auth, req, _| refunds::refund_update_core(state, auth.merchant_account, req), + |state, auth: auth::AuthenticationData, req, _| { + refunds::refund_update_core(state, auth.merchant_account, req) + }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index fbd2fa81207..e5e68fb4a85 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -58,7 +58,7 @@ pub async fn setup_intents_create( state.into_inner(), &req, create_payment_req, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fed284955b3..545f94cfeb4 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3450,9 +3450,12 @@ impl ProfileCreateBridge for api::ProfileCreate { .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); + let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers - .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .async_map(|headers| { + cards::create_encrypted_data(&key_manager_state, key_store, headers) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3567,9 +3570,12 @@ impl ProfileCreateBridge for api::ProfileCreate { .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); + let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers - .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .async_map(|headers| { + cards::create_encrypted_data(&key_manager_state, key_store, headers) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3828,9 +3834,12 @@ impl ProfileUpdateBridge for api::ProfileUpdate { }) .transpose()? .map(Secret::new); + let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers - .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .async_map(|headers| { + cards::create_encrypted_data(&key_manager_state, key_store, headers) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3929,9 +3938,12 @@ impl ProfileUpdateBridge for api::ProfileUpdate { }) .transpose()? .map(Secret::new); + let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers - .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .async_map(|headers| { + cards::create_encrypted_data(&key_manager_state, key_store, headers) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index fc7d717d5f1..19fbbf1952b 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -211,15 +211,18 @@ impl CustomerCreateBridge for customers::CustomerRequest { ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_customer_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_customer_billing_address - .async_map(|billing_address| create_encrypted_data(state, key_store, billing_address)) + .async_map(|billing_address| { + create_encrypted_data(key_state, key_store, billing_address) + }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_customer_shipping_address = self.get_default_customer_shipping_address(); - let encrypted_customer_shipping_address = default_customer_shipping_address - .async_map(|shipping_address| create_encrypted_data(state, key_store, shipping_address)) + .async_map(|shipping_address| { + create_encrypted_data(key_state, key_store, shipping_address) + }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) @@ -1239,18 +1242,20 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_billing_address = self.get_default_customer_billing_address(); - let encrypted_customer_billing_address = default_billing_address - .async_map(|billing_address| create_encrypted_data(state, key_store, billing_address)) + .async_map(|billing_address| { + create_encrypted_data(key_manager_state, key_store, billing_address) + }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_shipping_address = self.get_default_customer_shipping_address(); - let encrypted_customer_shipping_address = default_shipping_address - .async_map(|shipping_address| create_encrypted_data(state, key_store, shipping_address)) + .async_map(|shipping_address| { + create_encrypted_data(key_manager_state, key_store, shipping_address) + }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 4c72fd6d125..005b5aeba6c 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -852,11 +852,11 @@ pub async fn create_payment_method( ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - + let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| cards::create_encrypted_data(state, key_store, billing)) + .async_map(|billing| cards::create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -964,11 +964,11 @@ pub async fn payment_method_intent_create( ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - + let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| cards::create_encrypted_data(state, key_store, billing)) + .async_map(|billing| cards::create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1251,9 +1251,9 @@ pub async fn create_pm_additional_data_update( api::PaymentMethodsData::Card(card.clone().into()) } }; - + let key_manager_state = state.into(); let pmd: Encryptable<Secret<serde_json::Value>> = - cards::create_encrypted_data(state, key_store, card) + cards::create_encrypted_data(&key_manager_state, key_store, card) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method data")?; @@ -1922,7 +1922,7 @@ impl pm_types::SavedPMLPaymentsInfo { let off_session_payment_flag = matches!( payment_intent.setup_future_usage, - Some(common_enums::FutureUsage::OffSession) + common_enums::FutureUsage::OffSession ); let profile_id = &payment_intent.profile_id; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5da298815e7..8419a600f39 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -663,11 +663,11 @@ pub async fn skip_locker_call_and_migrate_payment_method( let connector_mandate_details = serde_json::to_value(&connector_mandate_details_req) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details")?; - + let key_manager_state = (&state).into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(&state, key_store, billing)) + .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -688,7 +688,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( - create_encrypted_data(&state, key_store, payment_method_card_details) + create_encrypted_data(&key_manager_state, key_store, payment_method_card_details) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method card details")?, @@ -821,11 +821,11 @@ pub async fn get_client_secret_or_add_payment_method( let condition = req.card.is_some(); #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); - + let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(state, key_store, billing)) + .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -973,7 +973,7 @@ pub async fn add_payment_method_data( if client_secret_expired { return Err((errors::ApiErrorResponse::ClientSecretExpired).into()); }; - + let key_manager_state = (&state).into(); match pmd { api_models::payment_methods::PaymentMethodCreateData::Card(card) => { helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?; @@ -1045,10 +1045,9 @@ pub async fn add_payment_method_data( card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()), saved_to_locker: true, }; - let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( - &state, + &key_manager_state, &key_store, PaymentMethodsData::Card(updated_card), ) @@ -1139,10 +1138,11 @@ pub async fn add_payment_method( let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; + let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(state, key_store, billing)) + .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1316,7 +1316,7 @@ pub async fn add_payment_method( let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { - create_encrypted_data(state, key_store, updated_pmd) + create_encrypted_data(&key_manager_state, key_store, updated_pmd) }) .await .transpose() @@ -1407,10 +1407,10 @@ pub async fn insert_payment_method( .card .clone() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - + let key_manager_state = state.into(); let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details .clone() - .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) + .async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1633,9 +1633,11 @@ pub async fn update_customer_payment_method( let updated_pmd = updated_card .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); - + let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd - .async_map(|updated_pmd| create_encrypted_data(&state, &key_store, updated_pmd)) + .async_map(|updated_pmd| { + create_encrypted_data(&key_manager_state, &key_store, updated_pmd) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -5341,7 +5343,7 @@ pub async fn delete_payment_method( } pub async fn create_encrypted_data<T>( - state: &routes::SessionState, + key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> @@ -5350,7 +5352,6 @@ where { let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); - let key_manager_state: KeyManagerState = state.into(); let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) @@ -5359,7 +5360,7 @@ where let secret_data = Secret::<_, masking::WithType>::new(encoded_data); let encrypted_data = domain::types::crypto_operation( - &key_manager_state, + key_manager_state, type_name!(payment_method::PaymentMethod), domain::types::CryptoOperation::Encrypt(secret_data), identifier.clone(), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 68f318958a2..ded1ce6a32f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -673,6 +673,7 @@ where )) } +#[cfg(feature = "v1")] // This function is intended for use when the feature being implemented is not aligned with the // core payment operations. #[allow(clippy::too_many_arguments, clippy::type_complexity)] @@ -873,6 +874,69 @@ where )) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments, clippy::type_complexity)] +#[instrument(skip_all, fields(payment_id, merchant_id))] +pub async fn payments_intent_operation_core<F, Req, Op, D>( + state: &SessionState, + _req_state: ReqState, + merchant_account: domain::MerchantAccount, + profile: domain::Profile, + key_store: domain::MerchantKeyStore, + operation: Op, + req: Req, + auth_flow: services::AuthFlow, + header_payload: HeaderPayload, +) -> RouterResult<(D, Req, Option<domain::Customer>)> +where + F: Send + Clone + Sync, + Req: Authenticate + Clone, + Op: Operation<F, Req, Data = D> + Send + Sync, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); + + tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); + + let (operation, _validate_result) = operation + .to_validate_request()? + .validate_request(&req, &merchant_account)?; + + let payment_id = id_type::GlobalPaymentId::generate(state.conf.cell_information.id.clone()); + + tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); + + let operations::GetTrackerResponse { + operation, + mut payment_data, + } = operation + .to_get_tracker()? + .get_trackers( + state, + &payment_id, + &req, + &merchant_account, + &profile, + &key_store, + auth_flow, + &header_payload, + ) + .await?; + + let (_operation, customer) = operation + .to_domain()? + .get_customer_details( + state, + &mut payment_data, + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("Failed while fetching/creating customer")?; + Ok((payment_data, req, customer)) +} + #[instrument(skip_all)] #[cfg(feature = "v1")] pub async fn call_decision_manager<F, D>( @@ -1245,6 +1309,52 @@ where ) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn payments_intent_core<F, Res, Req, Op, D>( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + profile: domain::Profile, + key_store: domain::MerchantKeyStore, + operation: Op, + req: Req, + auth_flow: services::AuthFlow, + header_payload: HeaderPayload, +) -> RouterResponse<Res> +where + F: Send + Clone + Sync, + Op: Operation<F, Req, Data = D> + Send + Sync + Clone, + Req: Debug + Authenticate + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + Res: transformers::ToResponse<F, D, Op>, +{ + let (payment_data, _req, customer) = payments_intent_operation_core::<_, _, _, _>( + &state, + req_state, + merchant_account, + profile, + key_store, + operation.clone(), + req, + auth_flow, + header_payload.clone(), + ) + .await?; + + Res::generate_response( + payment_data, + customer, + auth_flow, + &state.base_url, + operation, + &state.conf.connector_request_reference_id_config, + None, + None, + header_payload.x_hs_latency, + ) +} + fn is_start_pay<Op: Debug>(operation: &Op) -> bool { format!("{operation:?}").eq("PaymentStart") } @@ -5963,7 +6073,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { #[cfg(feature = "v2")] fn get_capture_method(&self) -> Option<enums::CaptureMethod> { - self.payment_intent.capture_method + Some(self.payment_intent.capture_method) } } @@ -6044,6 +6154,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.mandate_id = Some(mandate_id); } + #[cfg(feature = "v1")] fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, @@ -6051,6 +6162,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_intent.setup_future_usage = Some(setup_future_usage); } + #[cfg(feature = "v2")] + fn set_setup_future_usage_in_payment_intent( + &mut self, + setup_future_usage: storage_enums::FutureUsage, + ) { + self.payment_intent.setup_future_usage = setup_future_usage; + } + #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, @@ -6265,7 +6384,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { &mut self, setup_future_usage: storage_enums::FutureUsage, ) { - self.payment_intent.setup_future_usage = Some(setup_future_usage); + self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c3a47a740c6..7c97516192e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1567,10 +1567,12 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( .or(parsed_customer_data.phone_country_code.clone()), }) .or(temp_customer_data); - + let key_manager_state = state.into(); payment_data.payment_intent.customer_details = raw_customer_details .clone() - .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) + .async_map(|customer_details| { + create_encrypted_data(&key_manager_state, key_store, customer_details) + }) .await .transpose() .change_context(errors::StorageError::EncryptionError) @@ -3172,11 +3174,7 @@ pub fn authenticate_client_secret( } else { let current_timestamp = common_utils::date_time::now(); - let session_expiry = payment_intent.session_expiry.unwrap_or( - payment_intent - .created_at - .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), - ); + let session_expiry = payment_intent.session_expiry; fp_utils::when(current_timestamp > session_expiry, || { Err(errors::ApiErrorResponse::ClientSecretExpired) @@ -5927,6 +5925,7 @@ pub async fn config_skip_saving_wallet_at_connector( }) } +#[cfg(feature = "v1")] pub async fn override_setup_future_usage_to_on_session<F, D>( db: &dyn StorageInterface, payment_data: &mut D, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index efbe9bc8fcf..56b198c5381 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -28,6 +28,9 @@ pub mod payments_incremental_authorization; #[cfg(feature = "v1")] pub mod tax_calculation; +#[cfg(feature = "v2")] +pub mod payment_create_intent; + use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; @@ -35,6 +38,8 @@ use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; +#[cfg(feature = "v2")] +pub use self::payment_create_intent::PaymentCreateIntent; pub use self::payment_response::PaymentResponse; #[cfg(feature = "v1")] pub use self::{ @@ -93,6 +98,7 @@ pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { } } +#[cfg(feature = "v1")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, @@ -101,6 +107,15 @@ pub struct ValidateResult { pub requeue: bool, } +#[cfg(feature = "v2")] +#[derive(Clone)] +pub struct ValidateResult { + pub merchant_id: common_utils::id_type::MerchantId, + pub storage_scheme: enums::MerchantStorageScheme, + pub requeue: bool, +} + +#[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub trait ValidateRequest<F, R, D> { fn validate_request<'b>( @@ -110,6 +125,22 @@ pub trait ValidateRequest<F, R, D> { ) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>; } +#[cfg(feature = "v2")] +pub trait ValidateRequest<F, R, D> { + fn validate_request<'b>( + &'b self, + request: &R, + merchant_account: &domain::MerchantAccount, + ) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>; +} + +#[cfg(feature = "v2")] +pub struct GetTrackerResponse<'a, F: Clone, R, D> { + pub operation: BoxedOperation<'a, F, R, D>, + pub payment_data: D, +} + +#[cfg(feature = "v1")] pub struct GetTrackerResponse<'a, F: Clone, R, D> { pub operation: BoxedOperation<'a, F, R, D>, pub customer_details: Option<CustomerDetails>, @@ -118,6 +149,7 @@ pub struct GetTrackerResponse<'a, F: Clone, R, D> { pub mandate_type: Option<api::MandateTransactionType>, } +#[cfg(feature = "v1")] #[async_trait] pub trait GetTracker<F: Clone, D, R>: Send { #[allow(clippy::too_many_arguments)] @@ -133,8 +165,26 @@ pub trait GetTracker<F: Clone, D, R>: Send { ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; } +#[cfg(feature = "v2")] +#[async_trait] +pub trait GetTracker<F: Clone, D, R>: Send { + #[allow(clippy::too_many_arguments)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &common_utils::id_type::GlobalPaymentId, + request: &R, + merchant_account: &domain::MerchantAccount, + profile: &domain::Profile, + mechant_key_store: &domain::MerchantKeyStore, + auth_flow: services::AuthFlow, + header_payload: &api::HeaderPayload, + ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; +} + #[async_trait] pub trait Domain<F: Clone, R, D>: Send + Sync { + #[cfg(feature = "v1")] /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, @@ -145,6 +195,16 @@ pub trait Domain<F: Clone, R, D>: Send + Sync { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; + #[cfg(feature = "v2")] + /// This will fetch customer details, (this operation is flow specific) + async fn get_customer_details<'a>( + &'a self, + state: &SessionState, + payment_data: &mut D, + merchant_key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn make_pm_data<'a>( &'a self, @@ -344,13 +404,12 @@ where #[instrument(skip_all)] #[cfg(feature = "v2")] - async fn get_or_create_customer_details<'a>( + async fn get_customer_details<'a>( &'a self, - state: &SessionState, - payment_data: &mut D, - _request: Option<CustomerDetails>, - merchant_key_store: &domain::MerchantKeyStore, - storage_scheme: enums::MerchantStorageScheme, + _state: &SessionState, + _payment_data: &mut D, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, @@ -449,13 +508,12 @@ where #[instrument(skip_all)] #[cfg(feature = "v2")] - async fn get_or_create_customer_details<'a>( + async fn get_customer_details<'a>( &'a self, - state: &SessionState, - payment_data: &mut D, - _request: Option<CustomerDetails>, - merchant_key_store: &domain::MerchantKeyStore, - storage_scheme: enums::MerchantStorageScheme, + _state: &SessionState, + _payment_data: &mut D, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, @@ -554,12 +612,11 @@ where #[instrument(skip_all)] #[cfg(feature = "v2")] - async fn get_or_create_customer_details<'a>( + async fn get_customer_details<'a>( &'a self, - state: &SessionState, - payment_data: &mut D, - _request: Option<CustomerDetails>, - merchant_key_store: &domain::MerchantKeyStore, + _state: &SessionState, + _payment_data: &mut D, + _merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( @@ -617,6 +674,7 @@ impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectReque where for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Data = D>, { + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -635,6 +693,24 @@ where Ok((Box::new(self), None)) } + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn get_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut D, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult< + ( + BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5dccea54f52..9ec2438ddb3 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1361,8 +1361,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen ); let billing_address = payment_data.address.get_payment_billing(); + let key_manager_state = state.into(); let billing_details = billing_address - .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) + .async_map(|billing_details| { + create_encrypted_data(&key_manager_state, key_store, billing_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1370,7 +1373,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_address = payment_data.address.get_shipping(); let shipping_details = shipping_address - .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) + .async_map(|shipping_details| { + create_encrypted_data(&key_manager_state, key_store, shipping_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index a715aadf334..779b2d29c06 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -39,10 +39,7 @@ use crate::{ utils as core_utils, }, db::StorageInterface, - routes::{ - app::{ReqState, SessionStateInfo}, - SessionState, - }, + routes::{app::ReqState, SessionState}, services, types::{ self, @@ -844,14 +841,13 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let raw_customer_details = customer .map(|customer| CustomerData::foreign_try_from(customer.clone())) .transpose()?; - let session_state = state.session_state(); - + let key_manager_state = state.into(); // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Create Request let customer_details = raw_customer_details .clone() .async_map(|customer_details| { - create_encrypted_data(&session_state, key_store, customer_details) + create_encrypted_data(&key_manager_state, key_store, customer_details) }) .await .transpose() diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs new file mode 100644 index 00000000000..c0b66b44468 --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -0,0 +1,312 @@ +use std::marker::PhantomData; + +use api_models::{enums::FrmSuggestion, payments::PaymentsCreateIntentRequest}; +use async_trait::async_trait; +use common_utils::{ + errors::CustomResult, + ext_traits::{AsyncExt, ValueExt}, +}; +use error_stack::ResultExt; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult, StorageErrorExt}, + payments::{self, cards::create_encrypted_data, helpers, operations}, + }, + routes::{app::ReqState, SessionState}, + services, + types::{ + api, domain, + storage::{self, enums}, + }, +}; + +#[derive(Debug, Clone, Copy)] +pub struct PaymentCreateIntent; + +impl<F: Send + Clone> Operation<F, PaymentsCreateIntentRequest> for &PaymentCreateIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult< + &(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync), + > { + Ok(*self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> + { + Ok(*self) + } + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>)> { + Ok(*self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> + { + Ok(*self) + } +} + +impl<F: Send + Clone> Operation<F, PaymentsCreateIntentRequest> for PaymentCreateIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult< + &(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync), + > { + Ok(self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> + { + Ok(self) + } + fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>> { + Ok(self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> + { + Ok(self) + } +} + +type PaymentsCreateIntentOperation<'b, F> = + BoxedOperation<'b, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>; + +#[async_trait] +impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest> + for PaymentCreateIntent +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &common_utils::id_type::GlobalPaymentId, + request: &PaymentsCreateIntentRequest, + merchant_account: &domain::MerchantAccount, + profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, + _header_payload: &api::HeaderPayload, + ) -> RouterResult< + operations::GetTrackerResponse< + 'a, + F, + PaymentsCreateIntentRequest, + payments::PaymentIntentData<F>, + >, + > { + let db = &*state.store; + let key_manager_state = &state.into(); + + let storage_scheme = merchant_account.storage_scheme; + // Derivation of directly supplied Billing Address data in our Payment Create Request + // Encrypting our Billing Address Details to be stored in Payment Intent + let billing_address = request + .billing + .clone() + .async_map(|billing_details| { + create_encrypted_data(key_manager_state, key_store, billing_details) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt billing details")? + .map(|encrypted_value| { + encrypted_value.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to deserialize decrypted value to Address")?; + + // Derivation of directly supplied Shipping Address data in our Payment Create Request + // Encrypting our Shipping Address Details to be stored in Payment Intent + let shipping_address = request + .shipping + .clone() + .async_map(|shipping_details| { + create_encrypted_data(key_manager_state, key_store, shipping_details) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")? + .map(|encrypted_value| { + encrypted_value.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to deserialize decrypted value to Address")?; + let payment_intent_domain = + hyperswitch_domain_models::payments::PaymentIntent::create_domain_model_from_request( + payment_id, + merchant_account, + profile, + request.clone(), + billing_address, + shipping_address, + ) + .await?; + + let payment_intent = db + .insert_payment_intent( + key_manager_state, + payment_intent_domain, + key_store, + storage_scheme, + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { + message: format!( + "Payment Intent with payment_id {} already exists", + payment_id.get_string_repr() + ), + }) + .attach_printable("failed while inserting new payment intent")?; + + let payment_data = payments::PaymentIntentData { + flow: PhantomData, + payment_intent, + }; + + let get_trackers_response = operations::GetTrackerResponse { + operation: Box::new(self), + payment_data, + }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest> + for PaymentCreateIntent +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + _state: &'b SessionState, + _req_state: ReqState, + payment_data: payments::PaymentIntentData<F>, + _customer: Option<domain::Customer>, + _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + _key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: api::HeaderPayload, + ) -> RouterResult<( + PaymentsCreateIntentOperation<'b, F>, + payments::PaymentIntentData<F>, + )> + where + F: 'b + Send, + { + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone> + ValidateRequest<F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>> + for PaymentCreateIntent +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + _request: &PaymentsCreateIntentRequest, + merchant_account: &'a domain::MerchantAccount, + ) -> RouterResult<( + PaymentsCreateIntentOperation<'b, F>, + operations::ValidateResult, + )> { + Ok(( + Box::new(self), + operations::ValidateResult { + merchant_id: merchant_account.get_id().to_owned(), + storage_scheme: merchant_account.storage_scheme, + requeue: false, + }, + )) + } +} + +#[async_trait] +impl<F: Clone + Send> Domain<F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>> + for PaymentCreateIntent +{ + #[instrument(skip_all)] + async fn get_customer_details<'a>( + &'a self, + state: &SessionState, + payment_data: &mut payments::PaymentIntentData<F>, + merchant_key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult< + ( + BoxedOperation<'a, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + // validate customer_id if sent in the request + if let Some(id) = payment_data.payment_intent.customer_id.clone() { + state + .store + .find_customer_by_global_id( + &state.into(), + id.get_string_repr(), + &payment_data.payment_intent.merchant_id, + merchant_key_store, + storage_scheme, + ) + .await?; + } + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut payments::PaymentIntentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + ) -> RouterResult<( + PaymentsCreateIntentOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + async fn get_connector<'a>( + &'a self, + _merchant_account: &domain::MerchantAccount, + state: &SessionState, + _request: &PaymentsCreateIntentRequest, + _payment_intent: &storage::PaymentIntent, + _merchant_key_store: &domain::MerchantKeyStore, + ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { + helpers::get_connector_default(state, None).await + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _payment_data: &mut payments::PaymentIntentData<F>, + ) -> CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 2257c42f446..58f591e5c1b 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -640,6 +640,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector not found")?; + let key_manager_state = db.into(); + // For PayPal, if we call TaxJar for tax calculation, we need to call the connector again to update the order amount so that we can confirm the updated amount and order details. Therefore, we will store the required changes in the database during the post_update_tracker call. if payment_data.should_update_in_post_update_tracker() { match router_data.response.clone() { @@ -653,7 +655,11 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd let shipping_details = shipping_address .clone() .async_map(|shipping_details| { - create_encrypted_data(db, key_store, shipping_details) + create_encrypted_data( + &key_manager_state, + key_store, + shipping_details, + ) }) .await .transpose() diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 45a358ab2d7..c1eae806ce0 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -847,11 +847,13 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .payment_intent .statement_descriptor_suffix .clone(); - + let key_manager_state = state.into(); let billing_details = payment_data .address .get_payment_billing() - .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) + .async_map(|billing_details| { + create_encrypted_data(&key_manager_state, key_store, billing_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -860,7 +862,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_details = payment_data .address .get_shipping() - .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) + .async_map(|shipping_details| { + create_encrypted_data(&key_manager_state, key_store, shipping_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index d72d25cdd56..c72dcb6f561 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -389,11 +389,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculati .tax_data .clone() .map(|tax_data| tax_data.shipping_details); + let key_manager_state = state.into(); let shipping_details = shipping_address .clone() .async_map(|shipping_details| { - create_encrypted_data(state, key_store, shipping_details) + create_encrypted_data(&key_manager_state, key_store, shipping_details) }) .await .transpose() diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index ee75536e7c9..213a9211c06 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -277,10 +277,12 @@ where let pm_card_details = resp.card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); - + let key_manager_state = state.into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details - .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) + .async_map(|pm_card| { + create_encrypted_data(&key_manager_state, key_store, pm_card) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -295,7 +297,9 @@ where }); pm_token_details - .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) + .async_map(|pm_card| { + create_encrypted_data(&key_manager_state, key_store, pm_card) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -307,7 +311,9 @@ where let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address - .async_map(|address| create_encrypted_data(state, key_store, address.clone())) + .async_map(|address| { + create_encrypted_data(&key_manager_state, key_store, address.clone()) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -627,7 +633,9 @@ where let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd - .async_map(|pmd| create_encrypted_data(state, key_store, pmd)) + .async_map(|pmd| { + create_encrypted_data(&key_manager_state, key_store, pmd) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 72e6c6b9979..63847b65f5a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -516,6 +516,79 @@ where } } +#[cfg(feature = "v2")] +impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsCreateIntentResponse +where + F: Clone, + Op: Debug, + D: OperationSessionGetters<F>, +{ + #[allow(clippy::too_many_arguments)] + fn generate_response( + payment_data: D, + _customer: Option<domain::Customer>, + _auth_flow: services::AuthFlow, + _base_url: &str, + operation: Op, + _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, + _connector_http_status_code: Option<u16>, + _external_latency: Option<u128>, + _is_latency_header_enabled: Option<bool>, + ) -> RouterResponse<Self> { + let payment_intent = payment_data.get_payment_intent(); + Ok(services::ApplicationResponse::JsonWithHeaders(( + Self { + id: payment_intent.id.clone(), + amount_details: api_models::payments::AmountDetails::foreign_from( + payment_intent.amount_details.clone(), + ), + client_secret: payment_intent.client_secret.clone(), + merchant_reference_id: payment_intent.merchant_reference_id.clone(), + routing_algorithm_id: payment_intent.routing_algorithm_id.clone(), + capture_method: payment_intent.capture_method, + authentication_type: payment_intent.authentication_type, + billing: payment_intent + .billing_address + .clone() + .map(|billing| billing.into_inner().expose()), + shipping: payment_intent + .shipping_address + .clone() + .map(|shipping| shipping.into_inner().expose()), + customer_id: payment_intent.customer_id.clone(), + customer_present: payment_intent.customer_present.clone(), + description: payment_intent.description.clone(), + return_url: payment_intent.return_url.clone(), + setup_future_usage: payment_intent.setup_future_usage, + apply_mit_exemption: payment_intent.apply_mit_exemption.clone(), + statement_descriptor: payment_intent.statement_descriptor.clone(), + order_details: payment_intent.order_details.clone().map(|order_details| { + order_details + .into_iter() + .map(|order_detail| order_detail.expose()) + .collect() + }), + allowed_payment_method_types: payment_intent.allowed_payment_method_types.clone(), + metadata: payment_intent.metadata.clone(), + connector_metadata: payment_intent.connector_metadata.clone(), + feature_metadata: payment_intent.feature_metadata.clone(), + payment_link_enabled: payment_intent.enable_payment_link.clone(), + payment_link_config: payment_intent + .payment_link_config + .clone() + .map(ForeignFrom::foreign_from), + request_incremental_authorization: payment_intent.request_incremental_authorization, + expires_on: payment_intent.session_expiry, + frm_metadata: payment_intent.frm_metadata.clone(), + request_external_three_ds_authentication: payment_intent + .request_external_three_ds_authentication + .clone(), + }, + vec![], + ))) + } +} + #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse where @@ -2168,6 +2241,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectDa }) } } + +#[cfg(feature = "v2")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + todo!(); + } +} + +#[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; @@ -2529,3 +2613,220 @@ impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails { } } } + +#[cfg(feature = "v2")] +impl ForeignFrom<api_models::payments::AmountDetails> + for hyperswitch_domain_models::payments::AmountDetails +{ + fn foreign_from(amount_details: api_models::payments::AmountDetails) -> Self { + Self { + order_amount: amount_details.order_amount().into(), + currency: amount_details.currency(), + shipping_cost: amount_details.shipping_cost(), + tax_details: amount_details.order_tax_amount().map(|order_tax_amount| { + diesel_models::TaxDetails { + default: Some(diesel_models::DefaultTax { order_tax_amount }), + payment_method_type: None, + } + }), + skip_external_tax_calculation: + hyperswitch_domain_models::payments::TaxCalculationOverride::foreign_from( + amount_details.skip_external_tax_calculation(), + ), + skip_surcharge_calculation: + hyperswitch_domain_models::payments::SurchargeCalculationOverride::foreign_from( + amount_details.skip_surcharge_calculation(), + ), + surcharge_amount: amount_details.surcharge_amount(), + tax_on_surcharge: amount_details.tax_on_surcharge(), + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails> + for api_models::payments::AmountDetails +{ + fn foreign_from(amount_details: hyperswitch_domain_models::payments::AmountDetails) -> Self { + Self::new(api_models::payments::AmountDetailsSetter { + order_amount: amount_details.order_amount.into(), + currency: amount_details.currency, + shipping_cost: amount_details.shipping_cost, + order_tax_amount: amount_details.tax_details.and_then(|tax_details| { + tax_details.default.map(|default| default.order_tax_amount) + }), + skip_external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from( + amount_details.skip_external_tax_calculation, + ), + skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from( + amount_details.skip_surcharge_calculation, + ), + surcharge_amount: amount_details.surcharge_amount, + tax_on_surcharge: amount_details.tax_on_surcharge, + }) + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<common_enums::TaxCalculationOverride> + for hyperswitch_domain_models::payments::TaxCalculationOverride +{ + fn foreign_from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self { + match tax_calculation_override { + common_enums::TaxCalculationOverride::Calculate => Self::Calculate, + common_enums::TaxCalculationOverride::Skip => Self::Skip, + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<hyperswitch_domain_models::payments::TaxCalculationOverride> + for common_enums::TaxCalculationOverride +{ + fn foreign_from( + tax_calculation_override: hyperswitch_domain_models::payments::TaxCalculationOverride, + ) -> Self { + match tax_calculation_override { + hyperswitch_domain_models::payments::TaxCalculationOverride::Calculate => { + Self::Calculate + } + hyperswitch_domain_models::payments::TaxCalculationOverride::Skip => Self::Skip, + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<common_enums::SurchargeCalculationOverride> + for hyperswitch_domain_models::payments::SurchargeCalculationOverride +{ + fn foreign_from( + surcharge_calculation_override: common_enums::SurchargeCalculationOverride, + ) -> Self { + match surcharge_calculation_override { + common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate, + common_enums::SurchargeCalculationOverride::Skip => Self::Skip, + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<hyperswitch_domain_models::payments::SurchargeCalculationOverride> + for common_enums::SurchargeCalculationOverride +{ + fn foreign_from( + surcharge_calculation_override: hyperswitch_domain_models::payments::SurchargeCalculationOverride, + ) -> Self { + match surcharge_calculation_override { + hyperswitch_domain_models::payments::SurchargeCalculationOverride::Calculate => { + Self::Calculate + } + hyperswitch_domain_models::payments::SurchargeCalculationOverride::Skip => Self::Skip, + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> + for diesel_models::PaymentLinkConfigRequestForPayments +{ + fn foreign_from(config: api_models::admin::PaymentLinkConfigRequest) -> Self { + Self { + theme: config.theme, + logo: config.logo, + seller_name: config.seller_name, + sdk_layout: config.sdk_layout, + display_sdk_only: config.display_sdk_only, + enabled_saved_payment_method: config.enabled_saved_payment_method, + transaction_details: config.transaction_details.map(|transaction_details| { + transaction_details + .iter() + .map(|details| { + diesel_models::PaymentLinkTransactionDetails::foreign_from(details.clone()) + }) + .collect() + }), + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<api_models::admin::PaymentLinkTransactionDetails> + for diesel_models::PaymentLinkTransactionDetails +{ + fn foreign_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { + Self { + key: from.key, + value: from.value, + ui_configuration: from + .ui_configuration + .map(diesel_models::TransactionDetailsUiConfiguration::foreign_from), + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<api_models::admin::TransactionDetailsUiConfiguration> + for diesel_models::TransactionDetailsUiConfiguration +{ + fn foreign_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { + Self { + position: from.position, + is_key_bold: from.is_key_bold, + is_value_bold: from.is_value_bold, + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> + for api_models::admin::PaymentLinkConfigRequest +{ + fn foreign_from(config: diesel_models::PaymentLinkConfigRequestForPayments) -> Self { + Self { + theme: config.theme, + logo: config.logo, + seller_name: config.seller_name, + sdk_layout: config.sdk_layout, + display_sdk_only: config.display_sdk_only, + enabled_saved_payment_method: config.enabled_saved_payment_method, + transaction_details: config.transaction_details.map(|transaction_details| { + transaction_details + .iter() + .map(|details| { + api_models::admin::PaymentLinkTransactionDetails::foreign_from( + details.clone(), + ) + }) + .collect() + }), + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<diesel_models::PaymentLinkTransactionDetails> + for api_models::admin::PaymentLinkTransactionDetails +{ + fn foreign_from(from: diesel_models::PaymentLinkTransactionDetails) -> Self { + Self { + key: from.key, + value: from.value, + ui_configuration: from + .ui_configuration + .map(api_models::admin::TransactionDetailsUiConfiguration::foreign_from), + } + } +} + +#[cfg(feature = "v2")] +impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration> + for api_models::admin::TransactionDetailsUiConfiguration +{ + fn foreign_from(from: diesel_models::TransactionDetailsUiConfiguration) -> Self { + Self { + position: from.position, + is_key_bold: from.is_key_bold, + is_value_bold: from.is_value_bold, + } + } +} diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7417947cac8..46f45905448 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -208,6 +208,7 @@ pub async fn save_payout_data_to_locker( key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { let payouts = &payout_data.payouts; + let key_manager_state = state.into(); let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) = match payout_method_data { payouts::PayoutMethodData::Card(card) => { @@ -485,7 +486,7 @@ pub async fn save_payout_data_to_locker( }); ( Some( - cards::create_encrypted_data(state, key_store, pm_data) + cards::create_encrypted_data(&key_manager_state, key_store, pm_data) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?, diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index a37a91a55f1..2c3f76c88a0 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -373,7 +373,7 @@ async fn store_bank_details_in_payment_methods( payment_methods::PaymentMethodDataBankCreds, ), > = HashMap::new(); - + let key_manager_state = (&state).into(); for pm in payment_methods { if pm.payment_method == Some(enums::PaymentMethod::BankDebit) && pm.payment_method_data.is_some() @@ -480,8 +480,9 @@ async fn store_bank_details_in_payment_methods( ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); + let encrypted_data = - cards::create_encrypted_data(&state, &key_store, payment_method_data) + cards::create_encrypted_data(&key_manager_state, &key_store, payment_method_data) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; @@ -493,11 +494,14 @@ async fn store_bank_details_in_payment_methods( update_entries.push((pm.clone(), pm_update)); } else { let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); - let encrypted_data = - cards::create_encrypted_data(&state, &key_store, Some(payment_method_data)) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt customer details")?; + let encrypted_data = cards::create_encrypted_data( + &key_manager_state, + &key_store, + Some(payment_method_data), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; #[cfg(all( any(feature = "v1", feature = "v2"), diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c1eac13832b..bb852300222 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -74,6 +74,7 @@ pub mod headers { pub const X_DATE: &str = "X-Date"; pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; pub const X_REQUEST_ID: &str = "X-Request-Id"; + pub const X_PROFILE_ID: &str = "X-Profile-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub const X_CLIENT_VERSION: &str = "X-Client-Version"; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 560aa0d34ef..274ed6a5cc0 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -517,6 +517,8 @@ pub struct Payments; impl Payments { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/payments").app_data(web::Data::new(state)); + route = route + .service(web::resource("/create-intent").route(web::post().to(payments_create_intent))); route = route .service( web::resource("/{payment_id}/saved_payment_methods") diff --git a/crates/router/src/routes/currency.rs b/crates/router/src/routes/currency.rs index 80b74b5c0c2..4d800ddf1a5 100644 --- a/crates/router/src/routes/currency.rs +++ b/crates/router/src/routes/currency.rs @@ -39,7 +39,7 @@ pub async fn convert_forex( state.clone(), &req, (), - |state, _, _, _| { + |state, _: auth::AuthenticationData, _, _| { currency::convert_forex( state, amount.get_amount_as_i64(), diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 66ff1f8e323..536bca10f3d 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -23,7 +23,9 @@ pub async fn customers_create( state, &req, json_payload.into_inner(), - |state, auth, req, _| create_customer(state, auth.merchant_account, auth.key_store, req), + |state, auth: auth::AuthenticationData, req, _| { + create_customer(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -68,7 +70,7 @@ pub async fn customers_retrieve( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { retrieve_customer( state, auth.merchant_account, @@ -111,7 +113,9 @@ pub async fn customers_retrieve( state, &req, payload, - |state, auth, req, _| retrieve_customer(state, auth.merchant_account, auth.key_store, req), + |state, auth: auth::AuthenticationData, req, _| { + retrieve_customer(state, auth.merchant_account, auth.key_store, req) + }, &*auth, api_locking::LockAction::NotApplicable, )) @@ -132,7 +136,7 @@ pub async fn customers_list( state, &req, payload, - |state, auth, request, _| { + |state, auth: auth::AuthenticationData, request, _| { list_customers( state, auth.merchant_account.get_id().to_owned(), @@ -171,7 +175,7 @@ pub async fn customers_update( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { update_customer( state, auth.merchant_account, @@ -209,7 +213,7 @@ pub async fn customers_update( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { update_customer( state, auth.merchant_account, @@ -246,7 +250,9 @@ pub async fn customers_delete( state, &req, payload, - |state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store), + |state, auth: auth::AuthenticationData, req, _| { + delete_customer(state, auth.merchant_account, req, auth.key_store) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -278,7 +284,9 @@ pub async fn customers_delete( state, &req, payload, - |state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store), + |state, auth: auth::AuthenticationData, req, _| { + delete_customer(state, auth.merchant_account, req, auth.key_store) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -309,7 +317,7 @@ pub async fn get_customer_mandates( state, &req, customer_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { crate::core::mandate::get_customer_mandates( state, auth.merchant_account, diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 1a8c4410a53..22c1e3f1988 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -44,7 +44,7 @@ pub async fn retrieve_dispute( state, &req, dispute_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_dispute(state, auth.merchant_account, auth.profile_id, req) }, auth::auth_type( @@ -96,7 +96,7 @@ pub async fn retrieve_disputes_list( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_disputes_list(state, auth.merchant_account, None, req) }, auth::auth_type( @@ -149,7 +149,7 @@ pub async fn retrieve_disputes_list_profile( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_disputes_list( state, auth.merchant_account, @@ -189,7 +189,9 @@ pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) state, &req, (), - |state, auth, _, _| disputes::get_filters_for_disputes(state, auth.merchant_account, None), + |state, auth: auth::AuthenticationData, _, _| { + disputes::get_filters_for_disputes(state, auth.merchant_account, None) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -225,7 +227,7 @@ pub async fn get_disputes_filters_profile( state, &req, (), - |state, auth, _, _| { + |state, auth: auth::AuthenticationData, _, _| { disputes::get_filters_for_disputes( state, auth.merchant_account, @@ -275,7 +277,7 @@ pub async fn accept_dispute( state, &req, dispute_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::accept_dispute( state, auth.merchant_account, @@ -321,7 +323,7 @@ pub async fn submit_dispute_evidence( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::submit_evidence( state, auth.merchant_account, @@ -375,7 +377,7 @@ pub async fn attach_dispute_evidence( state, &req, attach_evidence_request, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::attach_evidence( state, auth.merchant_account, @@ -427,7 +429,7 @@ pub async fn retrieve_dispute_evidence( state, &req, dispute_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_dispute_evidence(state, auth.merchant_account, auth.profile_id, req) }, auth::auth_type( @@ -470,7 +472,9 @@ pub async fn delete_dispute_evidence( state, &req, json_payload.into_inner(), - |state, auth, req, _| disputes::delete_evidence(state, auth.merchant_account, req), + |state, auth: auth::AuthenticationData, req, _| { + disputes::delete_evidence(state, auth.merchant_account, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -498,7 +502,7 @@ pub async fn get_disputes_aggregate( state, &req, query_param, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::get_aggregates_for_disputes(state, auth.merchant_account, None, req) }, auth::auth_type( @@ -528,7 +532,7 @@ pub async fn get_disputes_aggregate_profile( state, &req, query_param, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { disputes::get_aggregates_for_disputes( state, auth.merchant_account, diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index cec7439940c..dd11bee24bd 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -26,7 +26,7 @@ pub async fn ephemeral_key_create( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { helpers::make_ephemeral_key( state, req.get_merchant_reference_id(), @@ -53,7 +53,7 @@ pub async fn ephemeral_key_delete( state, &req, payload, - |state, _, req, _| helpers::delete_ephemeral_key(state, req), + |state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req), &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs index 028b00a6a6a..2ebb1176aea 100644 --- a/crates/router/src/routes/files.rs +++ b/crates/router/src/routes/files.rs @@ -44,7 +44,9 @@ pub async fn files_create( state, &req, create_file_request, - |state, auth, req, _| files_create_core(state, auth.merchant_account, auth.key_store, req), + |state, auth: auth::AuthenticationData, req, _| { + files_create_core(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::DashboardNoPermissionAuth, @@ -86,7 +88,9 @@ pub async fn files_delete( state, &req, file_id, - |state, auth, req, _| files_delete_core(state, auth.merchant_account, req), + |state, auth: auth::AuthenticationData, req, _| { + files_delete_core(state, auth.merchant_account, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::DashboardNoPermissionAuth, @@ -128,7 +132,7 @@ pub async fn files_retrieve( state, &req, file_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { files_retrieve_core(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( diff --git a/crates/router/src/routes/fraud_check.rs b/crates/router/src/routes/fraud_check.rs index f51becf251c..5e7b7f3ef62 100644 --- a/crates/router/src/routes/fraud_check.rs +++ b/crates/router/src/routes/fraud_check.rs @@ -19,7 +19,7 @@ pub async fn frm_fulfillment( state.clone(), &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: services::authentication::AuthenticationData, req, _| { frm_core::frm_fulfillment_core(state, auth.merchant_account, auth.key_store, req) }, &services::authentication::ApiKeyAuth, diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index d47ee3caec5..cb16d6e0505 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -137,6 +137,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsCompleteAuthorize | Flow::PaymentsManualUpdate | Flow::SessionUpdateTaxCalculation + | Flow::PaymentsCreateIntent | Flow::PaymentsPostSessionTokens => Self::Payments, Flow::PayoutsCreate diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 4435c59b423..c0ccbfa9f8f 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -42,7 +42,7 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { mandate::get_mandate(state, auth.merchant_account, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -67,7 +67,7 @@ pub async fn revoke_mandate( state, &req, mandate_id, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -111,7 +111,7 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index be6ef9009b8..783566335bc 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -72,7 +72,7 @@ pub async fn initiate_payment_link( state, &req, payload.clone(), - |state, auth, _, _| { + |state, auth: auth::AuthenticationData, _, _| { initiate_payment_link_flow( state, auth.merchant_account, @@ -108,7 +108,7 @@ pub async fn initiate_secure_payment_link( state, &req, payload.clone(), - |state, auth, _, _| { + |state, auth: auth::AuthenticationData, _, _| { initiate_secure_payment_link_flow( state, auth.merchant_account, @@ -160,7 +160,9 @@ pub async fn payments_link_list( state, &req, payload, - |state, auth, payload, _| list_payment_link(state, auth.merchant_account, payload), + |state, auth: auth::AuthenticationData, payload, _| { + list_payment_link(state, auth.merchant_account, payload) + }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) @@ -188,7 +190,7 @@ pub async fn payment_link_status( state, &req, payload.clone(), - |state, auth, _, _| { + |state, auth: auth::AuthenticationData, _, _| { get_payment_link_status( state, auth.merchant_account, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 77c072448a2..8d95ee64ad0 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -20,8 +20,8 @@ use crate::core::payment_methods::{ }; use crate::{ core::{ - api_locking, errors, - errors::utils::StorageErrorExt, + api_locking, + errors::{self, utils::StorageErrorExt}, payment_methods::{self as payment_methods_routes, cards}, }, services::{api, authentication as auth, authorization::permissions::Permission}, @@ -58,7 +58,7 @@ pub async fn create_payment_method_api( state, &req, json_payload.into_inner(), - |state, auth, req, _| async move { + |state, auth: auth::AuthenticationData, req, _| async move { Box::pin(cards::get_client_secret_or_add_payment_method( &state, req, @@ -87,7 +87,7 @@ pub async fn create_payment_method_api( state, &req, json_payload.into_inner(), - |state, auth, req, _| async move { + |state, auth: auth::AuthenticationDataV2, req, _| async move { Box::pin(create_payment_method( &state, req, @@ -116,7 +116,7 @@ pub async fn create_payment_method_intent_api( state, &req, json_payload.into_inner(), - |state, auth, req, _| async move { + |state, auth: auth::AuthenticationDataV2, req, _| async move { Box::pin(payment_method_intent_create( &state, req, @@ -162,7 +162,7 @@ pub async fn confirm_payment_method_intent_api( state, &req, inner_payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { let pm_id = pm_id.clone(); async move { Box::pin(payment_method_intent_confirm( @@ -198,7 +198,7 @@ pub async fn payment_method_update_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationDataV2, req, _| { update_payment_method( state, auth.merchant_account, @@ -231,7 +231,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, auth, pm, _| { + |state, auth: auth::AuthenticationDataV2, pm, _| { retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -258,7 +258,7 @@ pub async fn payment_method_delete_api( state, &req, payload, - |state, auth, pm, _| { + |state, auth: auth::AuthenticationDataV2, pm, _| { delete_payment_method(state, pm, auth.key_store, auth.merchant_account) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -397,7 +397,7 @@ pub async fn save_payment_method_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { Box::pin(cards::add_payment_method_data( state, req, @@ -430,7 +430,7 @@ pub async fn list_payment_method_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::list_payment_methods(state, auth.merchant_account, auth.key_store, req) }, &*auth, @@ -487,7 +487,7 @@ pub async fn list_customer_payment_method_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, @@ -549,7 +549,7 @@ pub async fn list_customer_payment_method_for_payment( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { list_customer_payment_method_util( state, auth.merchant_account, @@ -614,7 +614,7 @@ pub async fn list_customer_payment_method_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { list_customer_payment_method_util( state, auth.merchant_account, @@ -679,7 +679,7 @@ pub async fn list_customer_payment_method_api_client( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, @@ -708,7 +708,7 @@ pub async fn initiate_pm_collect_link_flow( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payment_methods_routes::initiate_pm_collect_link( state, auth.merchant_account, @@ -740,7 +740,7 @@ pub async fn render_pm_collect_link( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payment_methods_routes::render_pm_collect_link( state, auth.merchant_account, @@ -775,7 +775,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, auth, pm, _| { + |state, auth: auth::AuthenticationData, pm, _| { cards::retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -809,7 +809,7 @@ pub async fn payment_method_update_api( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::update_customer_payment_method( state, auth.merchant_account, @@ -848,7 +848,7 @@ pub async fn payment_method_delete_api( state, &req, pm, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) }, &*ephemeral_auth, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 7410c5ee363..829f295cacc 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -75,7 +75,7 @@ pub async fn payments_create( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { authorize_verify_select::<_>( payments::PaymentCreate, state, @@ -104,6 +104,62 @@ pub async fn payments_create( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateIntent, payment_id))] +pub async fn payments_create_intent( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsCreateIntentRequest>, +) -> impl Responder { + use hyperswitch_domain_models::payments::PaymentIntentData; + + let flow = Flow::PaymentsCreateIntent; + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationDataV2, req, req_state| { + payments::payments_intent_core::< + api_types::CreateIntent, + payment_types::PaymentsCreateIntentResponse, + _, + _, + PaymentIntentData<api_types::CreateIntent>, + >( + state, + req_state, + auth.merchant_account, + auth.profile, + auth.key_store, + payments::operations::PaymentCreateIntent, + req, + api::AuthFlow::Client, + header_payload.clone(), + ) + }, + match env::which() { + env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), + _ => auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth { + permission: Permission::PaymentWrite, + minimum_entity_level: EntityType::Profile, + }, + req.headers(), + ), + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))] pub async fn payments_start( @@ -131,7 +187,7 @@ pub async fn payments_start( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::Authorize, payment_types::PaymentsResponse, @@ -205,7 +261,7 @@ pub async fn payments_retrieve( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, @@ -276,7 +332,7 @@ pub async fn payments_retrieve_with_gateway_creds( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, @@ -337,7 +393,7 @@ pub async fn payments_update( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { authorize_verify_select::<_>( payments::PaymentUpdate, state, @@ -457,7 +513,7 @@ pub async fn payments_confirm( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { authorize_verify_select::<_>( payments::PaymentConfirm, state, @@ -500,7 +556,7 @@ pub async fn payments_capture( state, &req, payload, - |state, auth, payload, req_state| { + |state, auth: auth::AuthenticationData, payload, req_state| { payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, @@ -559,7 +615,7 @@ pub async fn payments_dynamic_tax_calculation( state, &req, payload, - |state, auth, payload, req_state| { + |state, auth: auth::AuthenticationData, payload, req_state| { payments::payments_core::< api_types::SdkSessionUpdate, payment_types::PaymentsDynamicTaxCalculationResponse, @@ -627,7 +683,7 @@ pub async fn payments_connector_session( state, &req, payload, - |state, auth, payload, req_state| { + |state, auth: auth::AuthenticationData, payload, req_state| { payments::payments_core::< api_types::Session, payment_types::PaymentsSessionResponse, @@ -688,7 +744,7 @@ pub async fn payments_redirect_response( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, @@ -738,7 +794,7 @@ pub async fn payments_redirect_response_with_creds_identifier( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, @@ -788,7 +844,7 @@ pub async fn payments_complete_authorize_redirect( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectCompleteAuthorize {}, @@ -843,7 +899,7 @@ pub async fn payments_complete_authorize( state, &req, payload, - |state, auth, _req, req_state| { + |state, auth: auth::AuthenticationData, _req, req_state| { payments::payments_core::< api_types::CompleteAuthorize, payment_types::PaymentsResponse, @@ -892,7 +948,7 @@ pub async fn payments_cancel( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::Void, payment_types::PaymentsResponse, @@ -934,7 +990,7 @@ pub async fn payments_list( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payments::list_payments(state, auth.merchant_account, None, auth.key_store, req) }, auth::auth_type( @@ -964,7 +1020,7 @@ pub async fn profile_payments_list( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payments::list_payments( state, auth.merchant_account, @@ -1177,7 +1233,7 @@ pub async fn payments_approve( state, &http_req, payload.clone(), - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, @@ -1241,7 +1297,7 @@ pub async fn payments_reject( state, &http_req, payload.clone(), - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::Void, payment_types::PaymentsResponse, @@ -1422,7 +1478,7 @@ pub async fn payments_incremental_authorization( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::IncrementalAuthorization, payment_types::PaymentsResponse, @@ -1471,7 +1527,7 @@ pub async fn payments_external_authentication( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payments::payment_external_authentication( state, auth.merchant_account, @@ -1519,7 +1575,7 @@ pub async fn post_3ds_payments_authorize( state, &req, payload, - |state, auth, req, req_state| { + |state, auth: auth::AuthenticationData, req, req_state| { <payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentAuthenticateCompleteAuthorize {}, state, @@ -1580,7 +1636,7 @@ pub async fn retrieve_extended_card_info( state, &req, payment_id, - |state, auth, payment_id, _| { + |state, auth: auth::AuthenticationData, payment_id, _| { payments::get_extended_card_info( state, auth.merchant_account.get_id().to_owned(), diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 28b2afe2bee..ad860195a2a 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -42,7 +42,7 @@ pub async fn payouts_create( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_create_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -71,7 +71,7 @@ pub async fn payouts_retrieve( state, &req, payout_retrieve_request, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_retrieve_core( state, auth.merchant_account, @@ -111,7 +111,7 @@ pub async fn payouts_update( state, &req, payout_update_payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_update_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -172,7 +172,7 @@ pub async fn payouts_cancel( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_cancel_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -198,7 +198,7 @@ pub async fn payouts_fulfill( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -224,7 +224,7 @@ pub async fn payouts_list( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_list_core( state, auth.merchant_account, @@ -264,7 +264,7 @@ pub async fn payouts_list_profile( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_list_core( state, auth.merchant_account, @@ -304,7 +304,7 @@ pub async fn payouts_list_by_filter( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_filtered_list_core( state, auth.merchant_account, @@ -344,7 +344,7 @@ pub async fn payouts_list_by_filter_profile( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_filtered_list_core( state, auth.merchant_account, @@ -384,7 +384,7 @@ pub async fn payouts_list_available_filters_for_merchant( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_list_available_filters_core(state, auth.merchant_account, None, req, &locale) }, auth::auth_type( @@ -417,7 +417,7 @@ pub async fn payouts_list_available_filters_for_profile( state, &req, payload, - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { payouts_list_available_filters_core( state, auth.merchant_account, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index e254447cdef..f2dc322af17 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -306,7 +306,9 @@ pub async fn toggle_connector_agnostic_mit( state, &req, json_payload.into_inner(), - |state, _, req, _| connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req), + |state, _: auth::AuthenticationData, req, _| { + connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 4c9194dac16..c76ee600efe 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -37,7 +37,7 @@ pub async fn refunds_create( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { refund_create_core( state, auth.merchant_account, @@ -100,7 +100,7 @@ pub async fn refunds_retrieve( state, &req, refund_request, - |state, auth, refund_request, _| { + |state, auth: auth::AuthenticationData, refund_request, _| { refund_response_wrapper( state, auth.merchant_account, @@ -155,7 +155,7 @@ pub async fn refunds_retrieve_with_body( state, &req, json_payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { refund_response_wrapper( state, auth.merchant_account, @@ -204,7 +204,9 @@ pub async fn refunds_update( state, &req, refund_update_req, - |state, auth, req, _| refund_update_core(state, auth.merchant_account, req), + |state, auth: auth::AuthenticationData, req, _| { + refund_update_core(state, auth.merchant_account, req) + }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) @@ -237,7 +239,9 @@ pub async fn refunds_list( state, &req, payload.into_inner(), - |state, auth, req, _| refund_list(state, auth.merchant_account, None, req), + |state, auth: auth::AuthenticationData, req, _| { + refund_list(state, auth.merchant_account, None, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -278,7 +282,7 @@ pub async fn refunds_list_profile( state, &req, payload.into_inner(), - |state, auth, req, _| { + |state, auth: auth::AuthenticationData, req, _| { refund_list( state, auth.merchant_account, @@ -326,7 +330,9 @@ pub async fn refunds_filter_list( state, &req, payload.into_inner(), - |state, auth, req, _| refund_filter_list(state, auth.merchant_account, req), + |state, auth: auth::AuthenticationData, req, _| { + refund_filter_list(state, auth.merchant_account, req) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -362,7 +368,9 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - state, &req, (), - |state, auth, _, _| get_filters_for_refunds(state, auth.merchant_account, None), + |state, auth: auth::AuthenticationData, _, _| { + get_filters_for_refunds(state, auth.merchant_account, None) + }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { @@ -401,7 +409,7 @@ pub async fn get_refunds_filters_profile( state, &req, (), - |state, auth, _, _| { + |state, auth: auth::AuthenticationData, _, _| { get_filters_for_refunds( state, auth.merchant_account, diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index f2996009f82..17c946c4810 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -23,7 +23,7 @@ pub async fn apple_pay_merchant_registration( state, &req, json_payload.into_inner(), - |state, auth, body, _| { + |state, auth: auth::AuthenticationData, body, _| { verification::verify_merchant_creds_for_applepay( state.clone(), body, @@ -59,7 +59,7 @@ pub async fn retrieve_apple_pay_verified_domains( state, &req, merchant_id.clone(), - |state, _, _, _| { + |state, _: auth::AuthenticationData, _, _| { verification::get_verified_apple_domains_with_mid_mca_id( state, merchant_id.to_owned(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 1c0463da934..579a4ac4ffd 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1262,6 +1262,10 @@ impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequ impl Authenticate for api_models::payments::PaymentsStartRequest {} // impl Authenticate for api_models::payments::PaymentsApproveRequest {} impl Authenticate for api_models::payments::PaymentsRejectRequest {} +#[cfg(feature = "v2")] +impl Authenticate for api_models::payments::PaymentsCreateIntentRequest {} +// #[cfg(feature = "v2")] +// impl Authenticate for api_models::payments::PaymentsCreateIntentResponse {} pub fn build_redirection_form( form: &RedirectForm, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 3731d8ee081..a731b7e6dbb 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -58,6 +58,13 @@ pub struct AuthenticationData { pub profile_id: Option<id_type::ProfileId>, } +#[derive(Clone, Debug)] +pub struct AuthenticationDataV2 { + pub merchant_account: domain::MerchantAccount, + pub key_store: domain::MerchantKeyStore, + pub profile: domain::Profile, +} + #[derive(Clone, Debug)] pub struct AuthenticationDataWithMultipleProfiles { pub merchant_account: domain::MerchantAccount, @@ -275,6 +282,12 @@ impl AuthInfo for AuthenticationData { } } +impl AuthInfo for AuthenticationDataV2 { + fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { + Some(self.merchant_account.get_id()) + } +} + impl AuthInfo for AuthenticationDataWithMultipleProfiles { fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { Some(self.merchant_account.get_id()) @@ -296,6 +309,9 @@ where #[derive(Debug)] pub struct ApiKeyAuth; +#[derive(Debug)] +pub struct ApiKeyAuthV2; + pub struct NoAuth; #[cfg(feature = "partial-auth")] @@ -349,6 +365,97 @@ where } } +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationDataV2, A> for ApiKeyAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationDataV2, AuthenticationType)> { + let api_key = get_api_key(request_headers) + .change_context(errors::ApiErrorResponse::Unauthorized)? + .trim(); + if api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("API key is empty"); + } + + let profile_id = + get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? + .get_required_value(headers::X_PROFILE_ID)?; + + let api_key = api_keys::PlaintextApiKey::from(api_key); + let hash_key = { + let config = state.conf(); + config.api_keys.get_inner().get_hash_key()? + }; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + let key_manager_state = &(&state.session_state()).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let profile = state + .store() + .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let auth = AuthenticationDataV2 { + merchant_account: merchant, + key_store, + profile, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth where @@ -531,6 +638,48 @@ where } } +#[cfg(feature = "partial-auth")] +#[async_trait] +impl<A, I> AuthenticateAndFetch<AuthenticationDataV2, A> for HeaderAuth<I> +where + A: SessionStateInfo + Sync, + I: AuthenticateAndFetch<AuthenticationDataV2, A> + + AuthenticateAndFetch<AuthenticationData, A> + + GetAuthType + + Sync + + Send, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationDataV2, AuthenticationType)> { + let (auth_data, auth_type): (AuthenticationData, AuthenticationType) = self + .0 + .authenticate_and_fetch(request_headers, state) + .await?; + let profile_id = + get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? + .get_required_value(headers::X_PROFILE_ID)?; + let key_manager_state = &(&state.session_state()).into(); + let profile = state + .store() + .find_business_profile_by_profile_id( + key_manager_state, + &auth_data.key_store, + &profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + let auth_data_v2 = AuthenticationDataV2 { + merchant_account: auth_data.merchant_account, + key_store: auth_data.key_store, + profile, + }; + Ok((auth_data_v2, auth_type)) + } +} + #[cfg(feature = "partial-auth")] async fn construct_authentication_data<A>( state: &A, @@ -1605,16 +1754,82 @@ where .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; - + let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, key_store, profile_id: payload.profile_id, }; Ok(( - auth.clone(), + auth, AuthenticationType::MerchantJwt { - merchant_id: auth.merchant_account.get_id().clone(), + merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationDataV2, A> for JWTAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationDataV2, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + let profile_id = + get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? + .get_required_value(headers::X_PROFILE_ID)?; + + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let profile = state + .store() + .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant account for the merchant id")?; + let merchant_id = merchant.get_id().clone(); + let auth = AuthenticationDataV2 { + merchant_account: merchant, + key_store, + profile, + }; + Ok(( + auth, + AuthenticationType::MerchantJwt { + merchant_id, user_id: Some(payload.user_id), }, )) @@ -1996,6 +2211,20 @@ pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult }) .transpose() } +pub fn get_id_type_by_key_from_headers<T: std::str::FromStr>( + key: String, + headers: &HeaderMap, +) -> RouterResult<Option<T>> { + get_header_value_by_key(key.clone(), headers)? + .map(|str_value| T::from_str(str_value)) + .transpose() + .map_err(|_err| { + error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: key, + expected_format: "Valid Id String".to_string(), + }) + }) +} pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> { headers diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 8d52e5dc11a..02951d1a188 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -265,10 +265,15 @@ pub async fn create_profile_from_merchant_account( .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into); + let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers .async_map(|headers| { - core::payment_methods::cards::create_encrypted_data(state, key_store, headers) + core::payment_methods::cards::create_encrypted_data( + &key_manager_state, + key_store, + headers, + ) }) .await .transpose() diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index aedf91a3ce5..1bd3d484418 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -16,12 +16,14 @@ pub use api_models::payments::{ PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VerifyRequest, VerifyResponse, WalletData, }; +#[cfg(feature = "v2")] +pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsCreateIntentResponse}; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, - PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, - SetupMandate, Void, + CreateConnectorCustomer, CreateIntent, IncrementalAuthorization, InitPayment, PSync, + PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, + Session, SetupMandate, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 674f418785c..8000aa37ec9 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -169,6 +169,8 @@ pub enum Flow { PaymentsFilters, /// Payments aggregates flow PaymentsAggregate, + /// Payments Create Intent flow + PaymentsCreateIntent, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate, diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql index 33a58538a8a..318e57d5951 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql @@ -86,6 +86,8 @@ ALTER TABLE payment_intent ALTER COLUMN currency DROP NOT NULL, ALTER COLUMN client_secret DROP NOT NULL, ALTER COLUMN profile_id DROP NOT NULL; +ALTER TABLE payment_intent ALTER COLUMN active_attempt_id SET NOT NULL; +ALTER TABLE payment_intent ALTER COLUMN session_expiry DROP NOT NULL; ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey; diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql index 33718e20500..eca7603e2b9 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql @@ -105,3 +105,9 @@ SET NOT NULL, SET NOT NULL, ALTER COLUMN client_secret SET NOT NULL; +ALTER TABLE payment_intent ALTER COLUMN session_expiry SET NOT NULL; + +-- This migration is to make fields optional in payment_intent table +ALTER TABLE payment_intent ALTER COLUMN active_attempt_id DROP NOT NULL; + +
feat
add payments create-intent flow for v2 (#6193)
e75b11e98ac4c8d37c842c8ee0ccf361dcb52793
2024-01-11 19:16:16
DEEPANSHU BANSAL
feat(connector): [BOA/CYB] Store AVS response in connector_metadata (#3271)
false
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 1e0856a9ccc..aeb3dafcfa2 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -205,7 +205,7 @@ impl ConnectorCommon for Bankofamerica { }; match response { transformers::BankOfAmericaErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -218,13 +218,13 @@ impl ConnectorCommon for Bankofamerica { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(ErrorResponse { diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index e024eb7a501..6abe1b634df 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -343,6 +343,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -658,10 +682,12 @@ pub struct BankOfAmericaClientReferenceResponse { id: String, status: BankofamericaPaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaErrorInformationResponse { id: String, @@ -674,6 +700,55 @@ pub struct BankOfAmericaErrorInformation { message: Option<String>, } +impl<F, T> + From<( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, + )> for types::RouterData<F, T, types::PaymentsResponseData> +{ + fn from( + (error_response, item, transaction_status): ( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + T, + types::PaymentsResponseData, + >, + Option<enums::AttemptStatus>, + ), + ) -> Self { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data + }, + } + } +} + fn get_error_response_if_failure( (info_response, status, http_code): ( &BankOfAmericaClientReferenceResponse, @@ -684,6 +759,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -706,7 +782,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference: None, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -752,26 +831,13 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - status: enums::AttemptStatus::Failure, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } } } } @@ -806,24 +872,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -858,24 +909,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -927,10 +963,12 @@ impl<F> app_response.application_information.status, item.data.request.is_auto_capture()?, )); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1213,8 +1251,8 @@ pub struct BankOfAmericaAuthenticationErrorResponse { #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaErrorResponse { - StandardError(BankOfAmericaStandardErrorResponse), AuthenticationError(BankOfAmericaAuthenticationErrorResponse), + StandardError(BankOfAmericaStandardErrorResponse), } #[derive(Debug, Deserialize, Clone)] @@ -1235,29 +1273,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<BankOfAmericaErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()), diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 33503102e4b..6c4ea4c61fe 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -124,7 +124,7 @@ impl ConnectorCommon for Cybersource { }; match response { transformers::CybersourceErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -137,13 +137,13 @@ impl ConnectorCommon for Cybersource { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(types::ErrorResponse { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index bc69fb78129..8ae2ce29e5b 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1105,6 +1105,8 @@ pub struct CybersourceClientReferenceResponse { id: String, status: CybersourcePaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, token_information: Option<CybersourceTokenInformation>, error_information: Option<CybersourceErrorInformation>, } @@ -1136,6 +1138,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { @@ -1152,10 +1178,11 @@ impl<F, T> From<( &CybersourceErrorInformationResponse, types::ResponseRouterData<F, CybersourcePaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, )> for types::RouterData<F, T, types::PaymentsResponseData> { fn from( - (error_response, item): ( + (error_response, item, transaction_status): ( &CybersourceErrorInformationResponse, types::ResponseRouterData< F, @@ -1163,25 +1190,35 @@ impl<F, T> T, types::PaymentsResponseData, >, + Option<enums::AttemptStatus>, ), ) -> Self { - Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message.clone(), - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }) + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data }, - ..item.data } } } @@ -1196,6 +1233,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -1229,7 +1267,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -1276,25 +1317,11 @@ impl<F> ..item.data }) } - CybersourcePaymentsResponse::ErrorInformation(error_response) => { - let error_reason = &error_response.error_information.reason; - Ok(Self { - response: Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }), - status: enums::AttemptStatus::Failure, - ..item.data - }) - } + CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))), } } } @@ -1330,7 +1357,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1367,7 +1394,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1556,10 +1583,12 @@ impl<F> )); let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1782,30 +1811,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<CybersourceErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); - + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()),
feat
[BOA/CYB] Store AVS response in connector_metadata (#3271)
00b58a99c819e7827588b2a81460ce56b4df903e
2023-12-01 15:51:11
likhinbopanna
ci(postman): Fixed adyen assertion failure (#3030)
false
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js index 6731d57fb69..b88beefec22 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js @@ -50,10 +50,10 @@ if (jsonData?.error?.type) { // Response body should have value "invalid_request" for "error type" if (jsonData?.error?.message) { pm.test( - "[POST]::/payments - Content check if value for 'error.message' matches 'The payment has not succeeded yet. Please pass a successful payment to initiate refund'", + "[POST]::/payments - Content check if value for 'error.message' matches 'This Payment could not be refund because it has a status of requires_confirmation. The expected state is succeeded, partially_captured'", function () { pm.expect(jsonData.error.message).to.eql( - "The payment has not succeeded yet. Please pass a successful payment to initiate refund", + "This Payment could not be refund because it has a status of requires_confirmation. The expected state is succeeded, partially_captured", ); }, );
ci
Fixed adyen assertion failure (#3030)
ee044a0be811a53842c69f64c27d9995d84b7040
2024-01-09 15:03:47
harsh-sharma-juspay
fix(outgoingwebhookevents): Throw an error when outgoing webhook events env var not found (#3291)
false
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 2b29a61b4a4..2bcfcfe974f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -126,6 +126,15 @@ impl KafkaSettings { )) })?; + common_utils::fp_utils::when( + self.outgoing_webhook_logs_topic.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Outgoing Webhook Logs topic must not be empty".into(), + )) + }, + )?; + Ok(()) } }
fix
Throw an error when outgoing webhook events env var not found (#3291)
4cc389aa7061304ba517e3ec612d1f793ab35e67
2024-08-20 21:45:33
Sakil Mostak
feat(core): [Payouts] add merchant_connector_id to payout_attempt and show in response (#5214)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 458e1ae9ff0..cf8200d6779 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -13958,6 +13958,12 @@ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, + "merchant_connector_id": { + "type": "string", + "description": "Unique identifier of the merchant connector account", + "example": "mca_sAD3OZLATetvjLOYhUSy", + "nullable": true + }, "status": { "$ref": "#/components/schemas/PayoutStatus" }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 8b082caa373..c479abc8d93 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -18780,6 +18780,12 @@ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", "nullable": true }, + "merchant_connector_id": { + "type": "string", + "description": "Unique identifier of the merchant connector account", + "example": "mca_sAD3OZLATetvjLOYhUSy", + "nullable": true + }, "status": { "$ref": "#/components/schemas/PayoutStatus" }, diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 60c08241d17..0010c2988e1 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -464,6 +464,10 @@ pub struct PayoutCreateResponse { #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, + /// Unique identifier of the merchant connector account + #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] + pub merchant_connector_id: Option<String>, + /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs index fe8bbd77a38..17600e0cd78 100644 --- a/crates/diesel_models/src/payout_attempt.rs +++ b/crates/diesel_models/src/payout_attempt.rs @@ -89,6 +89,7 @@ pub enum PayoutAttemptUpdate { UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, + merchant_connector_id: Option<String>, }, } @@ -108,6 +109,7 @@ pub struct PayoutAttemptUpdateInternal { pub last_modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, + pub merchant_connector_id: Option<String>, } impl Default for PayoutAttemptUpdateInternal { @@ -123,6 +125,7 @@ impl Default for PayoutAttemptUpdateInternal { business_label: None, connector: None, routing_info: None, + merchant_connector_id: None, last_modified_at: common_utils::date_time::now(), address_id: None, customer_id: None, @@ -166,9 +169,11 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { PayoutAttemptUpdate::UpdateRouting { connector, routing_info, + merchant_connector_id, } => Self { connector: Some(connector), routing_info, + merchant_connector_id, ..Default::default() }, } @@ -191,6 +196,7 @@ impl PayoutAttemptUpdate { last_modified_at, address_id, customer_id, + merchant_connector_id, } = self.into(); PayoutAttempt { payout_token: payout_token.or(source.payout_token), @@ -206,6 +212,7 @@ impl PayoutAttemptUpdate { last_modified_at, address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), + merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), ..source } } diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs index b863382b7cd..a1f08610f9c 100644 --- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs @@ -152,6 +152,7 @@ pub enum PayoutAttemptUpdate { UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, + merchant_connector_id: Option<String>, }, } @@ -169,6 +170,7 @@ pub struct PayoutAttemptUpdateInternal { pub routing_info: Option<serde_json::Value>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, + pub merchant_connector_id: Option<String>, } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { @@ -207,9 +209,11 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { PayoutAttemptUpdate::UpdateRouting { connector, routing_info, + merchant_connector_id, } => Self { connector: Some(connector), routing_info, + merchant_connector_id, ..Default::default() }, } diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 5b6ca5d67b7..325935f9f3c 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -545,7 +545,6 @@ pub async fn payouts_retrieve_core( complete_payout_retrieve( &state, &merchant_account, - &key_store, connector_call_type, &mut payout_data, ) @@ -637,15 +636,9 @@ pub async fn payouts_cancel_core( .attach_printable("Connector not found for payout cancellation")?, }; - cancel_payout( - &state, - &merchant_account, - &key_store, - &connector_data, - &mut payout_data, - ) - .await - .attach_printable("Payout cancellation failed for given Payout request")?; + cancel_payout(&state, &merchant_account, &connector_data, &mut payout_data) + .await + .attach_printable("Payout cancellation failed for given Payout request")?; } response_handler(&merchant_account, &payout_data).await @@ -996,6 +989,28 @@ pub async fn call_connector_payout( let payout_attempt = &payout_data.payout_attempt.to_owned(); let payouts = &payout_data.payouts.to_owned(); + // fetch merchant connector account if not present + if payout_data.merchant_connector_account.is_none() + || payout_data.payout_attempt.merchant_connector_id.is_none() + { + let merchant_connector_account = construct_profile_id_and_get_mca( + state, + merchant_account, + payout_data, + &connector_data.connector_name.to_string(), + payout_attempt + .merchant_connector_id + .clone() + .or(connector_data.merchant_connector_id.clone()) + .as_ref(), + key_store, + false, + ) + .await?; + payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id(); + payout_data.merchant_connector_account = Some(merchant_connector_account); + } + // update connector_name if payout_data.payout_attempt.connector.is_none() || payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string()) @@ -1004,6 +1019,7 @@ pub async fn call_connector_payout( let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting { connector: connector_data.connector_name.to_string(), routing_info: payout_data.payout_attempt.routing_info.clone(), + merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(), }; let db = &*state.store; payout_data.payout_attempt = db @@ -1041,14 +1057,7 @@ pub async fn call_connector_payout( ); } // Eligibility flow - complete_payout_eligibility( - state, - merchant_account, - key_store, - connector_data, - payout_data, - ) - .await?; + complete_payout_eligibility(state, merchant_account, connector_data, payout_data).await?; // Create customer flow complete_create_recipient( state, @@ -1062,7 +1071,6 @@ pub async fn call_connector_payout( complete_create_recipient_disburse_account( state, merchant_account, - key_store, connector_data, payout_data, ) @@ -1071,7 +1079,6 @@ pub async fn call_connector_payout( Box::pin(complete_create_payout( state, merchant_account, - key_store, connector_data, payout_data, )) @@ -1147,14 +1154,9 @@ pub async fn create_recipient( ); if should_call_connector { // 1. Form router data - let router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -1290,7 +1292,6 @@ pub async fn create_recipient( pub async fn complete_payout_eligibility( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { @@ -1302,15 +1303,9 @@ pub async fn complete_payout_eligibility( .connector_name .supports_payout_eligibility(payout_data.payouts.payout_type) { - check_payout_eligibility( - state, - merchant_account, - key_store, - connector_data, - payout_data, - ) - .await - .attach_printable("Eligibility failed for given Payout request")?; + check_payout_eligibility(state, merchant_account, connector_data, payout_data) + .await + .attach_printable("Eligibility failed for given Payout request")?; } utils::when( @@ -1333,19 +1328,13 @@ pub async fn complete_payout_eligibility( pub async fn check_payout_eligibility( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -1446,7 +1435,6 @@ pub async fn check_payout_eligibility( pub async fn complete_create_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { @@ -1499,7 +1487,6 @@ pub async fn complete_create_payout( Box::pin(create_payout( state, merchant_account, - key_store, connector_data, payout_data, )) @@ -1513,19 +1500,13 @@ pub async fn complete_create_payout( pub async fn create_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let mut router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Get/Create access token access_token::create_access_token( @@ -1677,21 +1658,14 @@ async fn complete_payout_quote_steps_if_required<F>( pub async fn complete_payout_retrieve( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(connector_data) => { - create_payout_retrieve( - state, - merchant_account, - key_store, - &connector_data, - payout_data, - ) - .await - .attach_printable("Payout retrieval failed for given Payout request")?; + create_payout_retrieve(state, merchant_account, &connector_data, payout_data) + .await + .attach_printable("Payout retrieval failed for given Payout request")?; } api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) @@ -1705,19 +1679,13 @@ pub async fn complete_payout_retrieve( pub async fn create_payout_retrieve( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let mut router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Get/Create access token access_token::create_access_token( @@ -1820,7 +1788,6 @@ pub async fn update_retrieve_payout_tracker<F, T>( pub async fn complete_create_recipient_disburse_account( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { @@ -1831,15 +1798,9 @@ pub async fn complete_create_recipient_disburse_account( .connector_name .supports_vendor_disburse_account_create_for_payout() { - create_recipient_disburse_account( - state, - merchant_account, - key_store, - connector_data, - payout_data, - ) - .await - .attach_printable("Creation of customer failed")?; + create_recipient_disburse_account(state, merchant_account, connector_data, payout_data) + .await + .attach_printable("Creation of customer failed")?; } Ok(()) } @@ -1847,19 +1808,13 @@ pub async fn complete_create_recipient_disburse_account( pub async fn create_recipient_disburse_account( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -1932,19 +1887,13 @@ pub async fn create_recipient_disburse_account( pub async fn cancel_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -2042,14 +1991,9 @@ pub async fn fulfill_payout( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = core_utils::construct_payout_router_data( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let mut router_data = + core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) + .await?; // 2. Get/Create access token access_token::create_access_token( @@ -2243,6 +2187,7 @@ pub async fn response_handler( entity_type: payouts.entity_type.to_owned(), recurring: payouts.recurring, metadata: payouts.metadata, + merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(), status: payout_attempt.status.to_owned(), error_message: payout_attempt.error_message.to_owned(), error_code: payout_attempt.error_code, @@ -2540,6 +2485,28 @@ pub async fn make_payout_data( payouts::PayoutRequest::PayoutRetrieveRequest(_) => None, }; + let merchant_connector_account = + if payout_attempt.connector.is_some() && payout_attempt.merchant_connector_id.is_some() { + let connector_name = payout_attempt + .connector + .clone() + .get_required_value("connector_name")?; + Some( + payment_helpers::get_merchant_connector_account( + state, + merchant_account.get_id(), + None, + key_store, + &profile_id, + connector_name.as_str(), + payout_attempt.merchant_connector_id.as_ref(), + ) + .await?, + ) + } else { + None + }; + let payout_link = payouts .payout_link_id .clone() @@ -2559,7 +2526,7 @@ pub async fn make_payout_data( payouts, payout_attempt, payout_method_data: payout_method_data.to_owned(), - merchant_connector_account: None, + merchant_connector_account, should_terminate: false, profile_id, payout_link, @@ -2756,3 +2723,42 @@ pub async fn create_payout_link_db_entry( message: "payout link already exists".to_string(), }) } + +#[instrument(skip_all)] +pub async fn construct_profile_id_and_get_mca( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + payout_data: &mut PayoutData, + connector_name: &str, + merchant_connector_id: Option<&String>, + key_store: &domain::MerchantKeyStore, + should_validate: bool, +) -> RouterResult<payment_helpers::MerchantConnectorAccountType> { + let key_manager_state: &common_utils::types::keymanager::KeyManagerState = &state.into(); + let profile_id = core_utils::get_profile_id_from_business_details( + key_manager_state, + key_store, + payout_data.payout_attempt.business_country, + payout_data.payout_attempt.business_label.as_ref(), + merchant_account, + Some(&payout_data.payout_attempt.profile_id), + &*state.store, + should_validate, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payout_attempt")?; + + let merchant_connector_account = payment_helpers::get_merchant_connector_account( + state, + merchant_account.get_id(), + None, + key_store, + &profile_id, + connector_name, + merchant_connector_id, + ) + .await?; + + Ok(merchant_connector_account) +} diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs index d8df7271b71..e72d6c6631d 100644 --- a/crates/router/src/core/payouts/transformers.rs +++ b/crates/router/src/core/payouts/transformers.rs @@ -36,6 +36,7 @@ impl Self { payout_id: payout.payout_id, merchant_id: payout.merchant_id, + merchant_connector_id: payout_attempt.merchant_connector_id, amount: payout.amount, currency: payout.destination_currency, connector: payout_attempt.connector, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 980c983e050..02a10252cd3 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -45,52 +45,18 @@ pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW: &str = const IRRELEVANT_PAYMENT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_payment_id_in_dispute_flow"; const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow"; -#[cfg(feature = "payouts")] -#[instrument(skip_all)] -pub async fn get_mca_for_payout<'a>( - state: &'a SessionState, - connector_data: &api::ConnectorData, - merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, - payout_data: &PayoutData, -) -> RouterResult<helpers::MerchantConnectorAccountType> { - match payout_data.merchant_connector_account.to_owned() { - Some(mca) => Ok(mca), - None => { - let merchant_connector_account = helpers::get_merchant_connector_account( - state, - merchant_account.get_id(), - None, - key_store, - &payout_data.profile_id, - &connector_data.connector_name.to_string(), - connector_data.merchant_connector_id.as_ref(), - ) - .await?; - Ok(merchant_connector_account) - } - } -} - #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( - state: &'a SessionState, connector_data: &api::ConnectorData, merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { - let merchant_connector_account = get_mca_for_payout( - state, - connector_data, - merchant_account, - key_store, - payout_data, - ) - .await?; + let merchant_connector_account = payout_data + .merchant_connector_account + .clone() + .get_required_value("merchant_connector_account")?; let connector_name = connector_data.connector_name; - payout_data.merchant_connector_account = Some(merchant_connector_account.clone()); let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs index 8d2d62f2d37..aba6f2016ba 100644 --- a/crates/storage_impl/src/payouts/payout_attempt.rs +++ b/crates/storage_impl/src/payouts/payout_attempt.rs @@ -630,9 +630,11 @@ impl DataModelExt for PayoutAttemptUpdate { Self::UpdateRouting { connector, routing_info, + merchant_connector_id, } => DieselPayoutAttemptUpdate::UpdateRouting { connector, routing_info, + merchant_connector_id, }, } }
feat
[Payouts] add merchant_connector_id to payout_attempt and show in response (#5214)
96153824a73f359623bf77f199013d2ca9ff5e43
2025-02-11 16:59:58
Narayan Bhat
feat(payment_methods_session_v2): add payment methods session endpoints (#7107)
false
diff --git a/api-reference-v2/api-reference/customers/customers--list-saved-payment-methods.mdx b/api-reference-v2/api-reference/customers/customers--list-saved-payment-methods.mdx new file mode 100644 index 00000000000..ef5a27f9604 --- /dev/null +++ b/api-reference-v2/api-reference/customers/customers--list-saved-payment-methods.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/customers/{id}/saved-payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--create.mdx b/api-reference-v2/api-reference/payment-method-session/payment-method-session--create.mdx new file mode 100644 index 00000000000..b75390a47d1 --- /dev/null +++ b/api-reference-v2/api-reference/payment-method-session/payment-method-session--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/payment-method-session +--- diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--list-payment-methods.mdx b/api-reference-v2/api-reference/payment-method-session/payment-method-session--list-payment-methods.mdx new file mode 100644 index 00000000000..bbbaf01c297 --- /dev/null +++ b/api-reference-v2/api-reference/payment-method-session/payment-method-session--list-payment-methods.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payment-method-session/:id/list-payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--retrieve.mdx b/api-reference-v2/api-reference/payment-method-session/payment-method-session--retrieve.mdx new file mode 100644 index 00000000000..3f0ab4a7461 --- /dev/null +++ b/api-reference-v2/api-reference/payment-method-session/payment-method-session--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payment-method-session/:id +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx b/api-reference-v2/api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx new file mode 100644 index 00000000000..fab85e2a419 --- /dev/null +++ b/api-reference-v2/api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/payment-method-session/:id/update-saved-payment-method +--- diff --git a/api-reference-v2/api-reference/payment-methods/payment-methods--payment-methods-list.mdx b/api-reference-v2/api-reference/payment-methods/payment-methods--payment-methods-list.mdx new file mode 100644 index 00000000000..b7f8edccffa --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-methods--payment-methods-list.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payment-methods/{id}/list-enabled-payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index 11e716d6303..8fd3b64230b 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -55,7 +55,17 @@ "api-reference/payment-methods/payment-method--confirm-intent", "api-reference/payment-methods/payment-method--update", "api-reference/payment-methods/payment-method--retrieve", - "api-reference/payment-methods/payment-method--delete" + "api-reference/payment-methods/payment-method--delete", + "api-reference/payment-methods/list-saved-payment-methods-for-a-customer" + ] + }, + { + "group": "Payment Method Session", + "pages": [ + "api-reference/payment-method-session/payment-method-session--create", + "api-reference/payment-method-session/payment-method-session--retrieve", + "api-reference/payment-method-session/payment-method-session--list-payment-methods", + "api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method" ] }, { @@ -122,7 +132,8 @@ "api-reference/customers/customers--retrieve", "api-reference/customers/customers--update", "api-reference/customers/customers--delete", - "api-reference/customers/customers--list" + "api-reference/customers/customers--list", + "api-reference/customers/customers--list-saved-payment-methods" ] }, { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 96294f56a96..ba795d40594 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -2338,58 +2338,6 @@ ] } }, - "/v2/payment-methods/{id}/list-enabled-payment-methods": { - "get": { - "tags": [ - "Payment Methods" - ], - "summary": "Payment Methods - Payment Methods List", - "description": "List the payment methods eligible for a payment method.", - "operationId": "List Payment methods for a Payment Method Intent", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "The global payment method id", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "X-Profile-Id", - "in": "header", - "description": "Profile ID associated to the payment method intent", - "required": true, - "schema": { - "type": "string" - }, - "example": "pro_abcdefghijklmnop" - } - ], - "responses": { - "200": { - "description": "Get the payment methods", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentMethodListResponseForPayments" - } - } - } - }, - "404": { - "description": "No payment method found with the given id" - } - }, - "security": [ - { - "api_key": [], - "ephemeral_key": [] - } - ] - } - }, "/v2/payment-methods/{id}/confirm-intent": { "post": { "tags": [ @@ -2550,6 +2498,198 @@ ] } }, + "/v2/payment-method-session": { + "post": { + "tags": [ + "Payment Method Session" + ], + "summary": "Payment Method Session - Create", + "description": "Create a payment method session for a customer\nThis is used to list the saved payment methods for the customer\nThe customer can also add a new payment method using this session", + "operationId": "Create a payment method session", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodSessionRequest" + }, + "examples": { + "Create a payment method session with customer_id": { + "value": { + "customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Create the payment method session", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodsSessionResponse" + } + } + } + }, + "400": { + "description": "The request is invalid" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-method-session/:id": { + "get": { + "tags": [ + "Payment Method Session" + ], + "summary": "Payment Method Session - Retrieve", + "description": "Retrieve the payment method session", + "operationId": "Retrieve the payment method session", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method Session", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The payment method session is retrieved successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodsSessionResponse" + } + } + } + }, + "404": { + "description": "The request is invalid" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] + } + }, + "/v2/payment-method-session/:id/list-payment-methods": { + "get": { + "tags": [ + "Payment Method Session" + ], + "summary": "Payment Method Session - List Payment Methods", + "description": "List payment methods for the given payment method session.\nThis endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.", + "operationId": "List Payment methods for a Payment Method Session", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method Session", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The payment method session is retrieved successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodListResponse" + } + } + } + }, + "404": { + "description": "The request is invalid" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] + } + }, + "/v2/payment-method-session/:id/update-saved-payment-method": { + "put": { + "tags": [ + "Payment Method Session" + ], + "summary": "Payment Method Session - Update a saved payment method", + "description": "Update a saved payment method from the given payment method session.", + "operationId": "Update a saved payment method", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method Session", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodSessionUpdateSavedPaymentMethod" + }, + "examples": { + "Update the card holder name": { + "value": { + "payment_method_data": { + "card": { + "card_holder_name": "Narayan Bhat" + } + }, + "payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The payment method has been updated successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "404": { + "description": "The request is invalid" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] + } + }, "/v2/refunds": { "post": { "tags": [ @@ -6709,6 +6849,42 @@ } } }, + "ClientSecretResponse": { + "type": "object", + "description": "client_secret for the resource_id mentioned", + "required": [ + "id", + "resource_id", + "created_at", + "expires", + "secret" + ], + "properties": { + "id": { + "type": "string", + "description": "Client Secret id", + "maxLength": 32, + "minLength": 1 + }, + "resource_id": { + "$ref": "#/components/schemas/ResourceId" + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "time at which this client secret was created" + }, + "expires": { + "type": "string", + "format": "date-time", + "description": "time at which this client secret would expire" + }, + "secret": { + "type": "string", + "description": "client secret" + } + } + }, "Comparison": { "type": "object", "description": "Represents a single comparison condition.", @@ -7779,25 +7955,20 @@ "CustomerPaymentMethod": { "type": "object", "required": [ - "payment_method_id", + "id", "customer_id", "payment_method_type", + "payment_method_subtype", "recurring_enabled", "created", "requires_cvv", "is_default" ], "properties": { - "payment_token": { - "type": "string", - "description": "Token for payment method in temporary card locker which gets refreshed often", - "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef", - "nullable": true - }, - "payment_method_id": { + "id": { "type": "string", - "description": "The unique identifier of the customer.", - "example": "pm_iouuy468iyuowqs" + "description": "The unique identifier of the payment method.", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8" }, "customer_id": { "type": "string", @@ -7810,12 +7981,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "recurring_enabled": { "type": "boolean", @@ -7844,14 +8010,6 @@ "description": "A timestamp (ISO 8601 code) that determines when the payment method was created", "example": "2023-01-18T11:04:09.922Z" }, - "surcharge_details": { - "allOf": [ - { - "$ref": "#/components/schemas/SurchargeDetailsResponse" - } - ], - "nullable": true - }, "requires_cvv": { "type": "boolean", "description": "Whether this payment method requires CVV to be collected", @@ -7861,8 +8019,7 @@ "type": "string", "format": "date-time", "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used", - "example": "2024-02-24T11:04:09.922Z", - "nullable": true + "example": "2024-02-24T11:04:09.922Z" }, "is_default": { "type": "boolean", @@ -7891,11 +8048,6 @@ "$ref": "#/components/schemas/CustomerPaymentMethod" }, "description": "List of payment methods for customer" - }, - "is_guest_customer": { - "type": "boolean", - "description": "Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret)", - "nullable": true } } }, @@ -8059,7 +8211,7 @@ "default_payment_method_id": { "type": "string", "description": "The identifier for the default payment method.", - "example": "pm_djh2837dwduh890123", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8", "nullable": true, "maxLength": 64 } @@ -8137,7 +8289,7 @@ "default_payment_method_id": { "type": "string", "description": "The unique identifier of the payment method", - "example": "card_rGK4Vi5iSW70MY7J2mIg", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8", "nullable": true } }, @@ -8492,39 +8644,6 @@ } } }, - "EphemeralKeyCreateResponse": { - "type": "object", - "description": "ephemeral_key for the customer_id mentioned", - "required": [ - "customer_id", - "created_at", - "expires", - "secret" - ], - "properties": { - "customer_id": { - "type": "string", - "description": "customer_id to which this ephemeral key belongs to", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 64, - "minLength": 1 - }, - "created_at": { - "type": "integer", - "format": "int64", - "description": "time at which this ephemeral key was created" - }, - "expires": { - "type": "integer", - "format": "int64", - "description": "time at which this ephemeral key would expire" - }, - "secret": { - "type": "string", - "description": "ephemeral key" - } - } - }, "ErrorCategory": { "type": "string", "enum": [ @@ -11712,6 +11831,26 @@ } } }, + "NetworkTokenization": { + "type": "object", + "description": "The network tokenization configuration for creating the payment method session", + "required": [ + "enable" + ], + "properties": { + "enable": { + "$ref": "#/components/schemas/NetworkTokenizationToggle" + } + } + }, + "NetworkTokenizationToggle": { + "type": "string", + "description": "The network tokenization toggle, whether to enable or skip the network tokenization", + "enum": [ + "Enable", + "Skip" + ] + }, "NetworkTransactionIdAndCardDetails": { "type": "object", "required": [ @@ -12394,7 +12533,7 @@ ] }, "object": { - "$ref": "#/components/schemas/PaymentsResponse" + "$ref": "#/components/schemas/PaymentsRetrieveResponse" } } }, @@ -14247,7 +14386,8 @@ "PaymentMethodListResponse": { "type": "object", "required": [ - "payment_methods_enabled" + "payment_methods_enabled", + "customer_payment_methods" ], "properties": { "payment_methods_enabled": { @@ -14256,6 +14396,13 @@ "$ref": "#/components/schemas/ResponsePaymentMethodTypes" }, "description": "The list of payment methods that are enabled for the business profile" + }, + "customer_payment_methods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CustomerPaymentMethod" + }, + "description": "The list of saved payment methods of the customer" } } }, @@ -14338,11 +14485,6 @@ "example": "2024-02-24T11:04:09.922Z", "nullable": true }, - "ephemeral_key": { - "type": "string", - "description": "For Client based calls", - "nullable": true - }, "payment_method_data": { "allOf": [ { @@ -14368,6 +14510,72 @@ } ] }, + "PaymentMethodSessionRequest": { + "type": "object", + "required": [ + "customer_id" + ], + "properties": { + "customer_id": { + "type": "string", + "description": "The customer id for which the payment methods session is to be created", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44" + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "psp_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/PspTokenization" + } + ], + "nullable": true + }, + "network_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenization" + } + ], + "nullable": true + }, + "expires_in": { + "type": "integer", + "format": "int32", + "description": "The time (seconds ) when the session will expire\nIf not provided, the session will expire in 15 minutes", + "default": 900, + "example": 900, + "nullable": true, + "minimum": 0 + } + } + }, + "PaymentMethodSessionUpdateSavedPaymentMethod": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodUpdate" + }, + { + "type": "object", + "required": [ + "payment_method_id" + ], + "properties": { + "payment_method_id": { + "type": "string", + "description": "The payment method id of the payment method to be updated", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8" + } + } + } + ] + }, "PaymentMethodSpecificFeatures": { "oneOf": [ { @@ -14569,6 +14777,60 @@ }, "additionalProperties": false }, + "PaymentMethodsSessionResponse": { + "type": "object", + "required": [ + "id", + "customer_id", + "expires_at", + "client_secret" + ], + "properties": { + "id": { + "type": "string", + "example": "12345_pms_01926c58bc6e77c09e809964e72af8c8" + }, + "customer_id": { + "type": "string", + "description": "The customer id for which the payment methods session is to be created", + "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8" + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "psp_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/PspTokenization" + } + ], + "nullable": true + }, + "network_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenization" + } + ], + "nullable": true + }, + "expires_at": { + "type": "string", + "format": "date-time", + "description": "The iso timestamp when the session will expire\nTrying to retrieve the session or any operations on the session after this time will result in an error", + "example": "2023-01-18T11:04:09.922Z" + }, + "client_secret": { + "type": "string", + "description": "Client Secret" + } + } + }, "PaymentProcessingDetails": { "type": "object", "required": [ @@ -17858,6 +18120,23 @@ } } }, + "PspTokenization": { + "type": "object", + "description": "The Payment Service Provider Configuration for payment methods that are created using the payment method session", + "required": [ + "tokenization_type", + "connector_id" + ], + "properties": { + "tokenization_type": { + "$ref": "#/components/schemas/TokenizationType" + }, + "connector_id": { + "type": "string", + "description": "The merchant connector id to be used for tokenization" + } + } + }, "RealTimePaymentData": { "oneOf": [ { @@ -18567,6 +18846,21 @@ } } }, + "ResourceId": { + "oneOf": [ + { + "type": "object", + "required": [ + "customer" + ], + "properties": { + "customer": { + "type": "string" + } + } + } + ] + }, "ResponsePaymentMethodTypes": { "allOf": [ { @@ -20480,6 +20774,14 @@ } } }, + "TokenizationType": { + "type": "string", + "description": "The type of tokenization to use for the payment method", + "enum": [ + "single_use", + "multi_use" + ] + }, "TouchNGoRedirection": { "type": "object" }, diff --git a/config/development.toml b/config/development.toml index fc7a9427d8c..a7e33511f17 100644 --- a/config/development.toml +++ b/config/development.toml @@ -69,8 +69,8 @@ common_merchant_identifier = "COMMON MERCHANT IDENTIFIER" applepay_endpoint = "DOMAIN SPECIFIC ENDPOINT" [locker] -host = "" -host_rs = "" +host = "http://127.0.0.1:3000" +host_rs = "http://127.0.0.1:3000" mock_locker = true basilisk_host = "" locker_enabled = true @@ -83,9 +83,57 @@ fallback_api_key = "" redis_lock_timeout = 100 [jwekey] -vault_encryption_key = "" -rust_locker_encryption_key = "" -vault_private_key = "" +vault_encryption_key = """ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq +Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu +zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm +3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i +Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU +aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc +oQIDAQAB +-----END PUBLIC KEY----- +""" +rust_locker_encryption_key = """ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq +Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu +zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm +3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i +Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU +aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc +oQIDAQAB +-----END PUBLIC KEY----- +""" +vault_private_key = """ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEA5Z/K0JWds8iHhWCa+rj0rhOQX1nVs/ArQ1D0vh3UlSPR2vZU +TrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T9J37leN2guAARed6oYoTDEP/OoKt +nUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPIrXQSg16KDZQb0QTMntnsiPIJDbsO +GcdKytRAcNaokiKLnia1v13N3bk6dSplrj1YzawslZfgqD0eov4FjzBMoA19yNtl +VLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wgAPK2BjMQ2AMkUxx0ubbtw/9CeJ+b +FWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/AQIDAQABAoIBAGNekD1N0e5AZG1S +zh6cNb6zVrH8xV9WGtLJ0PAJJrrXwnQYT4m10DOIM0+Jo/+/ePXLq5kkRI9DZmPu +Q/eKWc+tInfN9LZUS6n0r3wCrZWMQ4JFlO5RtEWwZdDbtFPZqOwObz/treKL2JHw +9YXaRijR50UUf3e61YLRqd9AfX0RNuuG8H+WgU3Gwuh5TwRnljM3JGaDPHsf7HLS +tNkqJuByp26FEbOLTokZDbHN0sy7/6hufxnIS9AK4vp8y9mZAjghG26Rbg/H71mp +Z+Q6P1y7xdgAKbhq7usG3/o4Y1e9wnghHvFS7DPwGekHQH2+LsYNEYOir1iRjXxH +GUXOhfUCgYEA+cR9jONQFco8Zp6z0wdGlBeYoUHVMjThQWEblWL2j4RG/qQd/y0j +uhVeU0/PmkYK2mgcjrh/pgDTtPymc+QuxBi+lexs89ppuJIAgMvLUiJT67SBHguP +l4+oL9U78KGh7PfJpMKH+Pk5yc1xucAevk0wWmr5Tz2vKRDavFTPV+MCgYEA61qg +Y7yN0cDtxtqlZdMC8BJPFCQ1+s3uB0wetAY3BEKjfYc2O/4sMbixXzt5PkZqZy96 +QBUBxhcM/rIolpM3nrgN7h1nmJdk9ljCTjWoTJ6fDk8BUh8+0GrVhTbe7xZ+bFUN +UioIqvfapr/q/k7Ah2mCBE04wTZFry9fndrH2ssCgYEAh1T2Cj6oiAX6UEgxe2h3 +z4oxgz6efAO3AavSPFFQ81Zi+VqHflpA/3TQlSerfxXwj4LV5mcFkzbjfy9eKXE7 +/bjCm41tQ3vWyNEjQKYr1qcO/aniRBtThHWsVa6eObX6fOGN+p4E+txfeX693j3A +6q/8QSGxUERGAmRFgMIbTq0CgYAmuTeQkXKII4U75be3BDwEgg6u0rJq/L0ASF74 +4djlg41g1wFuZ4if+bJ9Z8ywGWfiaGZl6s7q59oEgg25kKljHQd1uTLVYXuEKOB3 +e86gJK0o7ojaGTf9lMZi779IeVv9uRTDAxWAA93e987TXuPAo/R3frkq2SIoC9Rg +paGidwKBgBqYd/iOJWsUZ8cWEhSE1Huu5rDEpjra8JPXHqQdILirxt1iCA5aEQou +BdDGaDr8sepJbGtjwTyiG8gEaX1DD+KsF2+dQRQdQfcYC40n8fKkvpFwrKjDj1ac +VuY3OeNxi+dC2r7HppP3O/MJ4gX/RJJfSrcaGP8/Ke1W5+jE97Qy +-----END RSA PRIVATE KEY----- +""" tunnel_private_key = "" [connectors.supported] diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index fe4ba7d9686..d78564ae53a 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -213,8 +213,8 @@ pub struct CustomerResponse { #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. - #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] - pub default_payment_method_id: Option<String>, + #[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] @@ -340,8 +340,8 @@ pub struct CustomerUpdateRequest { #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the payment method - #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] - pub default_payment_method_id: Option<String>, + #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] diff --git a/crates/api_models/src/ephemeral_key.rs b/crates/api_models/src/ephemeral_key.rs index fa61642e353..9f569b91f7a 100644 --- a/crates/api_models/src/ephemeral_key.rs +++ b/crates/api_models/src/ephemeral_key.rs @@ -19,51 +19,69 @@ pub struct EphemeralKeyCreateRequest { } #[cfg(feature = "v2")] -/// Information required to create an ephemeral key. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ResourceId { + #[schema(value_type = String)] + Customer(id_type::GlobalCustomerId), +} + +#[cfg(feature = "v2")] +/// Information required to create a client secret. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] -pub struct EphemeralKeyCreateRequest { - /// Customer ID for which an ephemeral key must be created - #[schema( - min_length = 32, - max_length = 64, - value_type = String, - example = "12345_cus_01926c58bc6e77c09e809964e72af8c8" - )] - pub customer_id: id_type::GlobalCustomerId, +pub struct ClientSecretCreateRequest { + /// Resource ID for which a client secret must be created + pub resource_id: ResourceId, } #[cfg(feature = "v2")] -/// ephemeral_key for the customer_id mentioned +/// client_secret for the resource_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] -pub struct EphemeralKeyResponse { - /// Ephemeral key id +pub struct ClientSecretResponse { + /// Client Secret id #[schema(value_type = String, max_length = 32, min_length = 1)] - pub id: id_type::EphemeralKeyId, - /// customer_id to which this ephemeral key belongs to - #[schema(value_type = String, max_length = 64, min_length = 32, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] - pub customer_id: id_type::GlobalCustomerId, - /// time at which this ephemeral key was created + pub id: id_type::ClientSecretId, + /// resource_id to which this client secret belongs to + #[schema(value_type = ResourceId)] + pub resource_id: ResourceId, + /// time at which this client secret was created pub created_at: time::PrimitiveDateTime, - /// time at which this ephemeral key would expire + /// time at which this client secret would expire pub expires: time::PrimitiveDateTime, #[schema(value_type=String)] - /// ephemeral key + /// client secret pub secret: Secret<String>, } +#[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } +#[cfg(feature = "v1")] +impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + #[cfg(feature = "v2")] -impl common_utils::events::ApiEventMetric for EphemeralKeyResponse { +impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } +#[cfg(feature = "v2")] +impl common_utils::events::ApiEventMetric for ClientSecretResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + +#[cfg(feature = "v1")] /// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 27cbbd614d6..2124ff1aff9 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -179,6 +179,16 @@ impl<T> ApiEventMetric for DisputesMetricsResponse<T> { Some(ApiEventsType::Miscellaneous) } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl ApiEventMetric for PaymentMethodIntentConfirmInternal { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethod { + payment_method_id: self.id.clone(), + payment_method_type: Some(self.request.payment_method_type), + payment_method_subtype: Some(self.request.payment_method_subtype), + }) + } +} #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentCreate { @@ -192,3 +202,15 @@ impl ApiEventMetric for DisputeListFilters { Some(ApiEventsType::ResourceListAPI) } } + +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentMethodSessionRequest {} + +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentMethodsSessionResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethodSession { + payment_method_session_id: self.id.clone(), + }) + } +} diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index c365445e102..4e672927284 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -160,7 +160,7 @@ impl ApiEventMetric for PaymentsRequest { } #[cfg(feature = "v2")] -impl ApiEventMetric for PaymentsResponse { +impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d15fdd74432..ba18cbba506 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -194,6 +194,20 @@ impl PaymentMethodIntentConfirm { } } +/// This struct is used internally only +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PaymentMethodIntentConfirmInternal { + pub id: id_type::GlobalPaymentMethodId, + pub request: PaymentMethodIntentConfirm, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm { + fn from(item: PaymentMethodIntentConfirmInternal) -> Self { + item.request + } +} #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] /// This struct is only used by and internal api to migrate payment method pub struct PaymentMethodMigrate { @@ -871,10 +885,6 @@ pub struct PaymentMethodResponse { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, - /// For Client based calls - #[schema(value_type=Option<String>)] - pub ephemeral_key: Option<masking::Secret<String>>, - pub payment_method_data: Option<PaymentMethodResponseData>, } @@ -1105,6 +1115,9 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { pub struct PaymentMethodListResponse { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>, + + /// The list of saved payment methods of the customer + pub customer_payment_methods: Vec<CustomerPaymentMethod>, } #[cfg(all( @@ -1797,8 +1810,6 @@ pub struct CustomerPaymentMethodsListResponse { pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, - /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) - pub is_guest_customer: Option<bool>, } #[cfg(all( @@ -1844,12 +1855,9 @@ pub struct CustomerDefaultPaymentMethodResponse { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { - /// Token for payment method in temporary card locker which gets refreshed often - #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] - pub payment_token: Option<String>, - /// The unique identifier of the customer. - #[schema(example = "pm_iouuy468iyuowqs")] - pub payment_method_id: String, + /// The unique identifier of the payment method. + #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub id: id_type::GlobalPaymentMethodId, /// The unique identifier of the customer. #[schema( @@ -1865,8 +1873,8 @@ pub struct CustomerPaymentMethod { pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType,example = "credit")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] @@ -1884,17 +1892,15 @@ pub struct CustomerPaymentMethod { #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, - /// Surcharge details for this saved card - pub surcharge_details: Option<SurchargeDetailsResponse>, - /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used - #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub last_used_at: Option<time::PrimitiveDateTime>, + #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601")] + pub last_used_at: time::PrimitiveDateTime, + /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, @@ -2299,6 +2305,7 @@ type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); + #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") @@ -2464,29 +2471,72 @@ impl From<(PaymentMethodRecord, id_type::MerchantId)> for customers::CustomerReq } } -// #[cfg(feature = "v2")] -// impl From<PaymentMethodRecord> for customers::CustomerRequest { -// fn from(record: PaymentMethodRecord) -> Self { -// Self { -// merchant_reference_id: Some(record.customer_id), -// name: record.name.unwrap(), -// email: record.email.unwrap(), -// phone: record.phone, -// description: None, -// phone_country_code: record.phone_country_code, -// default_billing_address: Some(payments::AddressDetails { -// city: Some(record.billing_address_city), -// country: record.billing_address_country, -// line1: Some(record.billing_address_line1), -// line2: record.billing_address_line2, -// state: Some(record.billing_address_state), -// line3: record.billing_address_line3, -// zip: Some(record.billing_address_zip), -// first_name: Some(record.billing_address_first_name), -// last_name: Some(record.billing_address_last_name), -// }), -// default_shipping_address: None, -// metadata: None, -// } -// } -// } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct PaymentMethodSessionRequest { + /// The customer id for which the payment methods session is to be created + #[schema(value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] + pub customer_id: id_type::GlobalCustomerId, + + /// The billing address details of the customer. This will also be used for any new payment methods added during the session + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, + + /// The tokenization type to be applied + #[schema(value_type = Option<PspTokenization>)] + pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, + + /// The network tokenization configuration if applicable + #[schema(value_type = Option<NetworkTokenization>)] + pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + + /// The time (seconds ) when the session will expire + /// If not provided, the session will expire in 15 minutes + #[schema(example = 900, default = 900)] + pub expires_in: Option<u32>, +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct PaymentMethodSessionUpdateSavedPaymentMethod { + /// The payment method id of the payment method to be updated + #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub payment_method_id: id_type::GlobalPaymentMethodId, + + /// The update request for the payment method update + #[serde(flatten)] + pub payment_method_update_request: PaymentMethodUpdate, +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct PaymentMethodsSessionResponse { + #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] + pub id: id_type::GlobalPaymentMethodSessionId, + + /// The customer id for which the payment methods session is to be created + #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] + pub customer_id: id_type::GlobalCustomerId, + + /// The billing address details of the customer. This will also be used for any new payment methods added during the session + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, + + /// The tokenization type to be applied + #[schema(value_type = Option<PspTokenization>)] + pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, + + /// The network tokenization configuration if applicable + #[schema(value_type = Option<NetworkTokenization>)] + pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + + /// The iso timestamp when the session will expire + /// Trying to retrieve the session or any operations on the session after this time will result in an error + #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub expires_at: time::PrimitiveDateTime, + + /// Client Secret + #[schema(value_type = String)] + pub client_secret: masking::Secret<String>, +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 295b1979f1f..820992025c1 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -27,12 +27,13 @@ use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; +#[cfg(feature = "v1")] +use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, - ephemeral_key::EphemeralKeyCreateResponse, mandates::RecurringDetails, refunds, }; diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index f99e3a450b2..ddefea542c2 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -285,7 +285,7 @@ pub enum OutgoingWebhookContent { #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum OutgoingWebhookContent { - #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] + #[schema(value_type = PaymentsRetrieveResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsRetrieveResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c4ee48ed5ac..2a5219f4dea 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3687,6 +3687,39 @@ pub enum FeatureStatus { Supported, } +/// The type of tokenization to use for the payment method +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + ToSchema, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum TokenizationType { + /// Create a single use token for the given payment method + /// The user might have to go through additional factor authentication when using the single use token if required by the payment method + SingleUse, + /// Create a multi use token for the given payment method + /// User will have to complete the additional factor authentication only once when creating the multi use token + /// This will create a mandate at the connector which can be used for recurring payments + MultiUse, +} + +/// The network tokenization toggle, whether to enable or skip the network tokenization +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub enum NetworkTokenizationToggle { + /// Enable network tokenization for the payment method + Enable, + /// Skip network tokenization for the payment method + Skip, +} + #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { diff --git a/crates/common_types/src/payment_methods.rs b/crates/common_types/src/payment_methods.rs index 702d8c0e700..9e80a029a22 100644 --- a/crates/common_types/src/payment_methods.rs +++ b/crates/common_types/src/payment_methods.rs @@ -124,3 +124,23 @@ where } common_utils::impl_to_sql_from_sql_json!(PaymentMethodsEnabled); + +/// The network tokenization configuration for creating the payment method session +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct NetworkTokenization { + /// Enable the network tokenization for payment methods that are created using the payment method session + #[schema(value_type = NetworkTokenizationToggle)] + pub enable: common_enums::NetworkTokenizationToggle, +} + +/// The Payment Service Provider Configuration for payment methods that are created using the payment method session +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct PspTokenization { + /// The tokenization type to be applied for the payment method + #[schema(value_type = TokenizationType)] + pub tokenization_type: common_enums::TokenizationType, + + /// The merchant connector id to be used for tokenization + #[schema(value_type = String)] + pub connector_id: common_utils::id_type::MerchantConnectorAccountId, +} diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index e8c2b2d5a0b..52fc0daacf5 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -484,12 +484,21 @@ impl<T: Clone> Encryptable<T> { F: FnOnce(T) -> CustomResult<U, errors::ParsingError>, U: Clone, { - // Option::map(self, f) let inner = self.inner; let encrypted = self.encrypted; let inner = f(inner)?; Ok(Encryptable { inner, encrypted }) } + + /// consume self and modify the inner value + pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> { + let encrypted_data = self.encrypted; + let masked_data = f(self.inner); + Encryptable { + inner: masked_data, + encrypted: encrypted_data, + } + } } impl<T: Clone> Deref for Encryptable<Secret<T>> { diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index bae525f4562..2e90d646e9e 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -112,8 +112,13 @@ pub enum ApiEventsType { poll_id: String, }, Analytics, - EphemeralKey { - key_id: id_type::EphemeralKeyId, + #[cfg(feature = "v2")] + ClientSecret { + key_id: id_type::ClientSecretId, + }, + #[cfg(feature = "v2")] + PaymentMethodSession { + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, }, } diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index ea90c00121e..30b6a3888da 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -2,8 +2,8 @@ //! The id type can be used to create specific id types with custom behaviour mod api_key; +mod client_secret; mod customer; -mod ephemeral_key; #[cfg(feature = "v2")] mod global_id; mod merchant; @@ -32,14 +32,14 @@ use thiserror::Error; pub use self::global_id::{ customer::GlobalCustomerId, payment::{GlobalAttemptId, GlobalPaymentId}, - payment_methods::GlobalPaymentMethodId, + payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId}, refunds::GlobalRefundId, CellId, }; pub use self::{ api_key::ApiKeyId, + client_secret::ClientSecretId, customer::CustomerId, - ephemeral_key::EphemeralKeyId, merchant::MerchantId, merchant_connector_account::MerchantConnectorAccountId, organization::OrganizationId, diff --git a/crates/common_utils/src/id_type/client_secret.rs b/crates/common_utils/src/id_type/client_secret.rs new file mode 100644 index 00000000000..b9d7f2e09e6 --- /dev/null +++ b/crates/common_utils/src/id_type/client_secret.rs @@ -0,0 +1,32 @@ +crate::id_type!( + ClientSecretId, + "A type for key_id that can be used for Ephemeral key IDs" +); +crate::impl_id_type_methods!(ClientSecretId, "key_id"); + +// This is to display the `ClientSecretId` as ClientSecretId(abcd) +crate::impl_debug_id_type!(ClientSecretId); +crate::impl_try_from_cow_str_id_type!(ClientSecretId, "key_id"); + +crate::impl_generate_id_id_type!(ClientSecretId, "csi"); +crate::impl_serializable_secret_id_type!(ClientSecretId); +crate::impl_queryable_id_type!(ClientSecretId); +crate::impl_to_sql_from_sql_id_type!(ClientSecretId); + +#[cfg(feature = "v2")] +impl crate::events::ApiEventMetric for ClientSecretId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::ClientSecret { + key_id: self.clone(), + }) + } +} + +crate::impl_default_id_type!(ClientSecretId, "key"); + +impl ClientSecretId { + /// Generate a key for redis + pub fn generate_redis_key(&self) -> String { + format!("cs_{}", self.get_string_repr()) + } +} diff --git a/crates/common_utils/src/id_type/ephemeral_key.rs b/crates/common_utils/src/id_type/ephemeral_key.rs deleted file mode 100644 index 071980fc6a4..00000000000 --- a/crates/common_utils/src/id_type/ephemeral_key.rs +++ /dev/null @@ -1,31 +0,0 @@ -crate::id_type!( - EphemeralKeyId, - "A type for key_id that can be used for Ephemeral key IDs" -); -crate::impl_id_type_methods!(EphemeralKeyId, "key_id"); - -// This is to display the `EphemeralKeyId` as EphemeralKeyId(abcd) -crate::impl_debug_id_type!(EphemeralKeyId); -crate::impl_try_from_cow_str_id_type!(EphemeralKeyId, "key_id"); - -crate::impl_generate_id_id_type!(EphemeralKeyId, "eki"); -crate::impl_serializable_secret_id_type!(EphemeralKeyId); -crate::impl_queryable_id_type!(EphemeralKeyId); -crate::impl_to_sql_from_sql_id_type!(EphemeralKeyId); - -impl crate::events::ApiEventMetric for EphemeralKeyId { - fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { - Some(crate::events::ApiEventsType::EphemeralKey { - key_id: self.clone(), - }) - } -} - -crate::impl_default_id_type!(EphemeralKeyId, "key"); - -impl EphemeralKeyId { - /// Generate a key for redis - pub fn generate_redis_key(&self) -> String { - format!("epkey_{}", self.get_string_repr()) - } -} diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index 1ad1bd96084..1e376dfe4de 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -5,7 +5,6 @@ pub(super) mod refunds; use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types}; use error_stack::ResultExt; -use serde_json::error; use thiserror::Error; use crate::{ @@ -27,6 +26,7 @@ pub(crate) enum GlobalEntity { Attempt, PaymentMethod, Refund, + PaymentMethodSession, } impl GlobalEntity { @@ -37,6 +37,7 @@ impl GlobalEntity { Self::PaymentMethod => "pm", Self::Attempt => "att", Self::Refund => "ref", + Self::PaymentMethodSession => "pms", } } } @@ -204,8 +205,8 @@ mod global_id_tests { let cell_id = CellId::from_str(cell_id_string).unwrap(); let global_id = GlobalId::generate(&cell_id, entity); - /// Generate a regex for globalid - /// Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890 + // Generate a regex for globalid + // Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890 let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap(); assert!(regex.is_match(&global_id.0 .0 .0)); diff --git a/crates/common_utils/src/id_type/global_id/payment_methods.rs b/crates/common_utils/src/id_type/global_id/payment_methods.rs index a4fec5e836a..b3b314e7fcb 100644 --- a/crates/common_utils/src/id_type/global_id/payment_methods.rs +++ b/crates/common_utils/src/id_type/global_id/payment_methods.rs @@ -19,12 +19,61 @@ use crate::{ #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalPaymentMethodId(GlobalId); +/// A global id that can be used to identify a payment method session +#[derive( + Debug, + Clone, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + diesel::expression::AsExpression, +)] +#[diesel(sql_type = diesel::sql_types::Text)] +pub struct GlobalPaymentMethodSessionId(GlobalId); + #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GlobalPaymentMethodIdError { #[error("Failed to construct GlobalPaymentMethodId")] ConstructionError, } +#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] +pub enum GlobalPaymentMethodSessionIdError { + #[error("Failed to construct GlobalPaymentMethodSessionId")] + ConstructionError, +} + +impl GlobalPaymentMethodSessionId { + /// Create a new GlobalPaymentMethodSessionId from cell id information + pub fn generate( + cell_id: &CellId, + ) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> { + let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession); + Ok(Self(global_id)) + } + + /// Get the string representation of the id + pub fn get_string_repr(&self) -> &str { + self.0.get_string_repr() + } + + /// Construct a redis key from the id to be stored in redis + pub fn get_redis_key(&self) -> String { + format!("payment_method_session:{}", self.get_string_repr()) + } +} + +#[cfg(feature = "v2")] +impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::PaymentMethodSession { + payment_method_session_id: self.clone(), + }) + } +} + impl crate::events::ApiEventMetric for GlobalPaymentMethodId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some( @@ -89,3 +138,38 @@ where Ok(Self(global_id)) } } + +impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId +where + DB: diesel::backend::Backend, + Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, +{ + type Row = Self; + fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { + Ok(row) + } +} + +impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId +where + DB: diesel::backend::Backend, + GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, +{ + fn to_sql<'b>( + &'b self, + out: &mut diesel::serialize::Output<'b, '_, DB>, + ) -> diesel::serialize::Result { + self.0.to_sql(out) + } +} + +impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId +where + DB: diesel::backend::Backend, + GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, +{ + fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + let global_id = GlobalId::from_sql(value)?; + Ok(Self(global_id)) + } +} diff --git a/crates/common_utils/src/types/authentication.rs b/crates/common_utils/src/types/authentication.rs index 2df81b2d3d4..331f1e2a659 100644 --- a/crates/common_utils/src/types/authentication.rs +++ b/crates/common_utils/src/types/authentication.rs @@ -35,3 +35,28 @@ pub enum AuthInfo { profile_ids: Vec<id_type::ProfileId>, }, } + +/// Enum for different resource types supported in client secret +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ResourceId { + /// Global Payment ID (Not exposed in api_models version of enum) + Payment(id_type::GlobalPaymentId), + /// Global Customer ID + Customer(id_type::GlobalCustomerId), + /// Global Payment Methods Session ID + PaymentMethodSession(id_type::GlobalPaymentMethodSessionId), +} + +#[cfg(feature = "v2")] +impl ResourceId { + /// Get string representation of enclosed ID type + pub fn to_str(&self) -> &str { + match self { + Self::Payment(id) => id.get_string_repr(), + Self::Customer(id) => id.get_string_repr(), + Self::PaymentMethodSession(id) => id.get_string_repr(), + } + } +} diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index 7bd7d8368a7..dc39059c135 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -84,7 +84,7 @@ pub struct CustomerNew { pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, - pub default_payment_method_id: Option<String>, + pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, @@ -166,7 +166,7 @@ pub struct Customer { pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, - pub default_payment_method_id: Option<String>, + pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, @@ -243,7 +243,7 @@ pub struct CustomerUpdateInternal { pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<pii::SecretSerdeValue>, - pub default_payment_method_id: Option<Option<String>>, + pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>, pub updated_by: Option<String>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, diff --git a/crates/diesel_models/src/ephemeral_key.rs b/crates/diesel_models/src/ephemeral_key.rs index c7fc103ed09..ede9f61b03e 100644 --- a/crates/diesel_models/src/ephemeral_key.rs +++ b/crates/diesel_models/src/ephemeral_key.rs @@ -1,30 +1,29 @@ #[cfg(feature = "v2")] use masking::{PeekInterface, Secret}; + #[cfg(feature = "v2")] -pub struct EphemeralKeyTypeNew { - pub id: common_utils::id_type::EphemeralKeyId, +pub struct ClientSecretTypeNew { + pub id: common_utils::id_type::ClientSecretId, pub merchant_id: common_utils::id_type::MerchantId, - pub customer_id: common_utils::id_type::GlobalCustomerId, pub secret: Secret<String>, - pub resource_type: ResourceType, + pub resource_id: common_utils::types::authentication::ResourceId, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -pub struct EphemeralKeyType { - pub id: common_utils::id_type::EphemeralKeyId, +pub struct ClientSecretType { + pub id: common_utils::id_type::ClientSecretId, pub merchant_id: common_utils::id_type::MerchantId, - pub customer_id: common_utils::id_type::GlobalCustomerId, - pub resource_type: ResourceType, + pub resource_id: common_utils::types::authentication::ResourceId, pub created_at: time::PrimitiveDateTime, pub expires: time::PrimitiveDateTime, pub secret: Secret<String>, } #[cfg(feature = "v2")] -impl EphemeralKeyType { +impl ClientSecretType { pub fn generate_secret_key(&self) -> String { - format!("epkey_{}", self.secret.peek()) + format!("cs_{}", self.secret.peek()) } } @@ -50,21 +49,3 @@ impl common_utils::events::ApiEventMetric for EphemeralKey { Some(common_utils::events::ApiEventsType::Miscellaneous) } } - -#[derive( - Clone, - Copy, - Debug, - serde::Serialize, - serde::Deserialize, - strum::Display, - strum::EnumString, - PartialEq, - Eq, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum ResourceType { - Payment, - PaymentMethod, -} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 1908edb8ad2..d9163b02aad 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -47,6 +47,9 @@ pub mod routing_algorithm; pub mod types; pub mod unified_translations; +#[cfg(feature = "v2")] +pub mod payment_methods_session; + #[allow(unused_qualifications)] pub mod schema; #[allow(unused_qualifications)] diff --git a/crates/diesel_models/src/payment_methods_session.rs b/crates/diesel_models/src/payment_methods_session.rs new file mode 100644 index 00000000000..dad3e995e01 --- /dev/null +++ b/crates/diesel_models/src/payment_methods_session.rs @@ -0,0 +1,11 @@ +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct PaymentMethodsSession { + pub id: common_utils::id_type::GlobalPaymentMethodSessionId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub billing: Option<common_utils::encryption::Encryption>, + pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, + pub network_tokeinzation: Option<common_types::payment_methods::NetworkTokenization>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub expires_at: time::PrimitiveDateTime, +} diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index 0b92cb2538c..b481c3e808d 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -1058,6 +1058,25 @@ lazy_static! { } ); + deutschebank_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails{ + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::NotSupported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + } + ); + deutschebank_supported_payment_methods }; diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index b503326f84c..58103c08faa 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -58,7 +58,7 @@ pub struct Customer { pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, - pub default_payment_method_id: Option<String>, + pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub merchant_reference_id: Option<id_type::CustomerId>, pub default_billing_address: Option<Encryption>, @@ -313,14 +313,14 @@ pub enum CustomerUpdate { connector_customer: Box<Option<pii::SecretSerdeValue>>, default_billing_address: Option<Encryption>, default_shipping_address: Option<Encryption>, - default_payment_method_id: Option<Option<String>>, + default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, status: Option<DeleteStatus>, }, ConnectorCustomer { connector_customer: Option<pii::SecretSerdeValue>, }, UpdateDefaultPaymentMethod { - default_payment_method_id: Option<Option<String>>, + default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, }, } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 71ad9ee9275..c8683919f7b 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -1,5 +1,7 @@ +#[cfg(feature = "v2")] +use api_models::payment_methods::PaymentMethodsData; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use common_utils::crypto::Encryptable; +use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable}; use common_utils::{ crypto::OptionalEncryptableValue, errors::{CustomResult, ParsingError, ValidationError}, @@ -9,10 +11,15 @@ use common_utils::{ use diesel_models::enums as storage_enums; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; +// specific imports because of using the macro +#[cfg(feature = "v2")] +use rustc_hash::FxHashMap; +#[cfg(feature = "v2")] +use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::type_encryption::OptionalEncryptableJsonType; +use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; use crate::{ mandates::{CommonMandateReference, PaymentsMandateReference}, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, @@ -75,16 +82,22 @@ pub struct PaymentMethod { } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethod { + /// The identifier for the payment method. Using this recurring payments can be made + pub id: common_utils::id_type::GlobalPaymentMethodId, + + /// The customer id against which the payment method is saved pub customer_id: common_utils::id_type::GlobalCustomerId, + + /// The merchant id against which the payment method is saved pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_type: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, - pub payment_method_data: - OptionalEncryptableJsonType<api_models::payment_methods::PaymentMethodsData>, + #[encrypt(ty = Value)] + pub payment_method_data: Option<Encryptable<PaymentMethodsData>>, pub locker_id: Option<VaultId>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, @@ -92,14 +105,15 @@ pub struct PaymentMethod { pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, - pub payment_method_billing_address: OptionalEncryptableValue, + #[encrypt(ty = Value)] + pub payment_method_billing_address: Option<Encryptable<Address>>, pub updated_by: Option<String>, pub locker_fingerprint_id: Option<String>, - pub id: common_utils::id_type::GlobalPaymentMethodId, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, - pub network_token_payment_method_data: OptionalEncryptableValue, + #[encrypt(ty = Value)] + pub network_token_payment_method_data: Option<Encryptable<Value>>, } impl PaymentMethod { @@ -431,76 +445,88 @@ impl super::behaviour::Conversion for PaymentMethod { async fn convert_back( state: &keymanager::KeyManagerState, - item: Self::DstType, + storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { + use common_utils::ext_traits::ValueExt; + use masking::ExposeInterface; + async { + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable( + EncryptedPaymentMethod { + payment_method_data: storage_model.payment_method_data, + payment_method_billing_address: storage_model + .payment_method_billing_address, + network_token_payment_method_data: storage_model + .network_token_payment_method_data, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentMethod::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; + + let payment_method_billing_address = data + .payment_method_billing_address + .map(|billing| { + billing.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Address")?; + + let payment_method_data = data + .payment_method_data + .map(|payment_method_data| { + payment_method_data + .deserialize_inner_value(|value| value.parse_value("Payment Method Data")) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Payment Method Data")?; + + let network_token_payment_method_data = + data.network_token_payment_method_data + .map(|network_token_payment_method_data| { + network_token_payment_method_data.map(|value| value.expose()) + }); + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - customer_id: item.customer_id, - merchant_id: item.merchant_id, - id: item.id, - created_at: item.created_at, - last_modified: item.last_modified, - payment_method_type: item.payment_method_type_v2, - payment_method_subtype: item.payment_method_subtype, - payment_method_data: item - .payment_method_data - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, - locker_id: item.locker_id.map(VaultId::generate), - last_used_at: item.last_used_at, - connector_mandate_details: item.connector_mandate_details.map(|cmd| cmd.into()), - customer_acceptance: item.customer_acceptance, - status: item.status, - network_transaction_id: item.network_transaction_id, - client_secret: item.client_secret, - payment_method_billing_address: item - .payment_method_billing_address - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, - updated_by: item.updated_by, - locker_fingerprint_id: item.locker_fingerprint_id, - version: item.version, - network_token_requestor_reference_id: item.network_token_requestor_reference_id, - network_token_locker_id: item.network_token_locker_id, - network_token_payment_method_data: item - .network_token_payment_method_data - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, + customer_id: storage_model.customer_id, + merchant_id: storage_model.merchant_id, + id: storage_model.id, + created_at: storage_model.created_at, + last_modified: storage_model.last_modified, + payment_method_type: storage_model.payment_method_type_v2, + payment_method_subtype: storage_model.payment_method_subtype, + payment_method_data, + locker_id: storage_model.locker_id.map(VaultId::generate), + last_used_at: storage_model.last_used_at, + connector_mandate_details: storage_model.connector_mandate_details.map(From::from), + customer_acceptance: storage_model.customer_acceptance, + status: storage_model.status, + network_transaction_id: storage_model.network_transaction_id, + client_secret: storage_model.client_secret, + payment_method_billing_address, + updated_by: storage_model.updated_by, + locker_fingerprint_id: storage_model.locker_fingerprint_id, + version: storage_model.version, + network_token_requestor_reference_id: storage_model + .network_token_requestor_reference_id, + network_token_locker_id: storage_model.network_token_locker_id, + network_token_payment_method_data, }) } .await @@ -541,6 +567,100 @@ impl super::behaviour::Conversion for PaymentMethod { } } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, router_derive::ToEncryption)] +pub struct PaymentMethodsSession { + pub id: common_utils::id_type::GlobalPaymentMethodSessionId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + #[encrypt(ty = Value)] + pub billing: Option<Encryptable<Address>>, + pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, + pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub expires_at: PrimitiveDateTime, +} + +#[cfg(feature = "v2")] +#[async_trait::async_trait] +impl super::behaviour::Conversion for PaymentMethodsSession { + type DstType = diesel_models::payment_methods_session::PaymentMethodsSession; + type NewDstType = diesel_models::payment_methods_session::PaymentMethodsSession; + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(Self::DstType { + id: self.id, + customer_id: self.customer_id, + billing: self.billing.map(|val| val.into()), + psp_tokenization: self.psp_tokenization, + network_tokeinzation: self.network_tokenization, + expires_at: self.expires_at, + }) + } + + async fn convert_back( + state: &keymanager::KeyManagerState, + storage_model: Self::DstType, + key: &Secret<Vec<u8>>, + key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + use common_utils::ext_traits::ValueExt; + + async { + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedPaymentMethodsSession::to_encryptable( + EncryptedPaymentMethodsSession { + billing: storage_model.billing, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentMethodsSession::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; + + let billing = data + .billing + .map(|billing| { + billing.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Address")?; + + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + id: storage_model.id, + customer_id: storage_model.customer_id, + billing, + psp_tokenization: storage_model.psp_tokenization, + network_tokenization: storage_model.network_tokeinzation, + expires_at: storage_model.expires_at, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting payment method data".to_string(), + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(Self::NewDstType { + id: self.id, + customer_id: self.customer_id, + billing: self.billing.map(|val| val.into()), + psp_tokenization: self.psp_tokenization, + network_tokeinzation: self.network_tokenization, + expires_at: self.expires_at, + }) + } +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index a4af7b1e131..cc6f1b0e411 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -131,12 +131,16 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for payment methods routes::payment_method::create_payment_method_api, routes::payment_method::create_payment_method_intent_api, - routes::payment_method::list_payment_methods, routes::payment_method::confirm_payment_method_intent_api, routes::payment_method::payment_method_update_api, routes::payment_method::payment_method_retrieve_api, routes::payment_method::payment_method_delete_api, - // routes::payment_method::list_customer_payment_method_api, + + //Routes for payment method session + routes::payment_method::payment_method_session_create, + routes::payment_method::payment_method_session_retrieve, + routes::payment_method::payment_method_session_list_payment_methods, + routes::payment_method::payment_method_session_update_saved_payment_method, //Routes for refunds routes::refunds::refunds_create, @@ -164,6 +168,8 @@ Never share your secret api keys. Keep them guarded and secure. common_types::refunds::StripeSplitRefundRequest, common_utils::types::ChargeRefunds, common_types::payment_methods::PaymentMethodsEnabled, + common_types::payment_methods::PspTokenization, + common_types::payment_methods::NetworkTokenization, common_types::refunds::SplitRefund, common_types::payments::ConnectorChargeResponseData, common_types::payments::StripeChargeResponseData, @@ -193,6 +199,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::customers::CustomerRequest, api_models::customers::CustomerUpdateRequest, api_models::customers::CustomerDeleteResponse, + api_models::ephemeral_key::ResourceId, api_models::payment_methods::PaymentMethodCreate, api_models::payment_methods::PaymentMethodIntentCreate, api_models::payment_methods::PaymentMethodIntentConfirm, @@ -493,6 +500,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkRequest, api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::payment_methods::PaymentMethodSubtypeSpecificData, + api_models::payment_methods::PaymentMethodSessionRequest, + api_models::payment_methods::PaymentMethodsSessionResponse, api_models::payments::PaymentsRetrieveResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, @@ -502,7 +511,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::mandates::MandateCardDetails, api_models::mandates::RecurringDetails, api_models::mandates::ProcessorPaymentToken, - api_models::ephemeral_key::EphemeralKeyCreateResponse, + api_models::ephemeral_key::ClientSecretResponse, api_models::payments::CustomerDetails, api_models::payments::GiftCardData, api_models::payments::GiftCardDetails, @@ -655,7 +664,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::feature_matrix::PaymentMethodSpecificFeatures, api_models::feature_matrix::CardSpecificFeatures, api_models::feature_matrix::SupportedPaymentMethod, + api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, common_utils::types::BrowserInformation, + api_models::enums::TokenizationType, + api_models::enums::NetworkTokenizationToggle, api_models::payments::PaymentAmountDetailsResponse, routes::payments::ForceSync, )), diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 4c0c201e290..3c1f66e6e76 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -322,27 +322,104 @@ pub async fn payment_method_update_api() {} #[cfg(feature = "v2")] pub async fn payment_method_delete_api() {} -/// Payment Methods - Payment Methods List +/// Payment Method Session - Create /// -/// List the payment methods eligible for a payment method. +/// Create a payment method session for a customer +/// This is used to list the saved payment methods for the customer +/// The customer can also add a new payment method using this session +#[cfg(feature = "v2")] +#[utoipa::path( + post, + path = "/v2/payment-method-session", + request_body( + content = PaymentMethodSessionRequest, + examples (( "Create a payment method session with customer_id" = ( + value =json!( { + "customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz" + }) + ))) + ), + responses( + (status = 200, description = "Create the payment method session", body = PaymentMethodsSessionResponse), + (status = 400, description = "The request is invalid") + ), + tag = "Payment Method Session", + operation_id = "Create a payment method session", + security(("api_key" = [])) +)] +pub fn payment_method_session_create() {} + +/// Payment Method Session - Retrieve +/// +/// Retrieve the payment method session #[cfg(feature = "v2")] #[utoipa::path( get, - path = "/v2/payment-methods/{id}/list-enabled-payment-methods", - params( - ("id" = String, Path, description = "The global payment method id"), - ( - "X-Profile-Id" = String, Header, - description = "Profile ID associated to the payment method intent", - example = "pro_abcdefghijklmnop" - ), + path = "/v2/payment-method-session/:id", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method Session"), ), responses( - (status = 200, description = "Get the payment methods", body = PaymentMethodListResponseForPayments), - (status = 404, description = "No payment method found with the given id") + (status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodsSessionResponse), + (status = 404, description = "The request is invalid") ), - tag = "Payment Methods", - operation_id = "List Payment methods for a Payment Method Intent", - security(("api_key" = [], "ephemeral_key" = [])) + tag = "Payment Method Session", + operation_id = "Retrieve the payment method session", + security(("ephemeral_key" = [])) +)] +pub fn payment_method_session_retrieve() {} + +/// Payment Method Session - List Payment Methods +/// +/// List payment methods for the given payment method session. +/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer. +#[cfg(feature = "v2")] +#[utoipa::path( + get, + path = "/v2/payment-method-session/:id/list-payment-methods", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method Session"), + ), + responses( + (status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponse), + (status = 404, description = "The request is invalid") + ), + tag = "Payment Method Session", + operation_id = "List Payment methods for a Payment Method Session", + security(("ephemeral_key" = [])) +)] +pub fn payment_method_session_list_payment_methods() {} + +/// Payment Method Session - Update a saved payment method +/// +/// Update a saved payment method from the given payment method session. +#[cfg(feature = "v2")] +#[utoipa::path( + put, + path = "/v2/payment-method-session/:id/update-saved-payment-method", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method Session"), + ), + request_body( + content = PaymentMethodSessionUpdateSavedPaymentMethod, + examples(( "Update the card holder name" = ( + value =json!( { + "payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3", + "payment_method_data": { + "card": { + "card_holder_name": "Narayan Bhat" + } + } + } + ) + ))) + ), + responses( + (status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse), + (status = 404, description = "The request is invalid") + ), + tag = "Payment Method Session", + operation_id = "Update a saved payment method", + security(("ephemeral_key" = [])) )] -pub fn list_payment_methods() {} +pub fn payment_method_session_update_saved_payment_method() {} diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 4d506449589..05d08f37ddd 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -215,5 +215,8 @@ pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str = /// Refund flow identifier used for performing GSM operations pub const REFUND_FLOW_STR: &str = "refund_flow"; +/// Default payment method session expiry +pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes + /// Authorize flow identifier used for performing GSM operations pub const AUTHORIZE_FLOW_STR: &str = "Authorize"; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index d9f0db4c2ac..5bdb0f0819e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -67,8 +67,10 @@ use crate::{ services::encryption, types::{ api::{self, payment_methods::PaymentMethodCreateExt}, + domain::types as domain_types, payment_methods as pm_types, storage::{ephemeral_key, PaymentMethodListContext}, + transformers::{ForeignFrom, ForeignTryFrom}, }, utils::ext_traits::OptionExt, }; @@ -852,6 +854,8 @@ pub async fn create_payment_method( merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResponse<api::PaymentMethodResponse> { + use common_utils::ext_traits::ValueExt; + req.validate()?; let db = &*state.store; @@ -870,14 +874,20 @@ pub async fn create_payment_method( .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; - let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req + let payment_method_billing_address = req .billing .clone() .async_map(|billing| cards::create_encrypted_data(key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt Payment method billing address")?; + .attach_printable("Unable to encrypt Payment method billing address")? + .map(|encoded_address| { + encoded_address.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to parse Payment method billing address")?; // create pm let payment_method_id = @@ -885,7 +895,7 @@ pub async fn create_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; - let (payment_method, ephemeral_key) = create_payment_method_for_intent( + let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, @@ -935,10 +945,7 @@ pub async fn create_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let resp = pm_transforms::generate_payment_method_response( - &payment_method, - Some(ephemeral_key), - )?; + let resp = pm_transforms::generate_payment_method_response(&payment_method)?; Ok(resp) } @@ -989,14 +996,20 @@ pub async fn payment_method_intent_create( .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; - let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req + let payment_method_billing_address = req .billing .clone() .async_map(|billing| cards::create_encrypted_data(key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt Payment method billing address")?; + .attach_printable("Unable to encrypt Payment method billing address")? + .map(|encoded_address| { + encoded_address.deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to parse Payment method billing address")?; // create pm entry @@ -1005,7 +1018,7 @@ pub async fn payment_method_intent_create( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; - let (payment_method, ephemeral_key) = create_payment_method_for_intent( + let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, @@ -1018,134 +1031,72 @@ pub async fn payment_method_intent_create( .await .attach_printable("Failed to add Payment method to DB")?; - let resp = - pm_transforms::generate_payment_method_response(&payment_method, Some(ephemeral_key))?; + let resp = pm_transforms::generate_payment_method_response(&payment_method)?; Ok(services::ApplicationResponse::Json(resp)) } +#[cfg(feature = "v2")] +trait PerformFilteringOnEnabledPaymentMethods { + fn perform_filtering(self) -> FilteredPaymentMethodsEnabled; +} + +#[cfg(feature = "v2")] +impl PerformFilteringOnEnabledPaymentMethods + for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled +{ + fn perform_filtering(self) -> FilteredPaymentMethodsEnabled { + FilteredPaymentMethodsEnabled(self.payment_methods_enabled) + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] -pub async fn payment_method_intent_confirm( - state: &SessionState, - req: api::PaymentMethodIntentConfirm, - merchant_account: &domain::MerchantAccount, - key_store: &domain::MerchantKeyStore, - pm_id: id_type::GlobalPaymentMethodId, -) -> RouterResponse<api::PaymentMethodResponse> { - let key_manager_state = &(state).into(); - req.validate()?; +pub async fn list_payment_methods_for_session( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + profile: domain::Profile, + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, +) -> RouterResponse<api::PaymentMethodListResponse> { + let key_manager_state = &(&state).into(); let db = &*state.store; - let payment_method = db - .find_payment_method( - &(state.into()), - key_store, - &pm_id, - merchant_account.storage_scheme, - ) + let payment_method_session = db + .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?; - when( - payment_method.status != enums::PaymentMethodStatus::AwaitingData, - || { - Err(errors::ApiErrorResponse::InvalidRequestData { - message: "Invalid pm_id provided: This Payment method cannot be confirmed" - .to_string(), - }) - }, - )?; - - let customer_id = payment_method.customer_id.to_owned(); - db.find_customer_by_global_id( - key_manager_state, - &customer_id, - merchant_account.get_id(), - key_store, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - - let payment_method_data = pm_types::PaymentMethodVaultingData::from(req.payment_method_data); + let payment_connector_accounts = db + .list_enabled_connector_accounts_by_profile_id( + key_manager_state, + profile.get_id(), + &key_store, + common_enums::ConnectorType::PaymentProcessor, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error when fetching merchant connector accounts")?; - let vaulting_result = vault_payment_method( - state, - &payment_method_data, - merchant_account, - key_store, - None, + let customer_payment_methods = list_customer_payment_method_core( + &state, + &merchant_account, + &key_store, + &payment_method_session.customer_id, ) - .await; - - let response = match vaulting_result { - Ok((vaulting_resp, fingerprint_id)) => { - let pm_update = create_pm_additional_data_update( - &payment_method_data, - state, - key_store, - Some(vaulting_resp.vault_id.get_string_repr().clone()), - Some(req.payment_method_type), - Some(req.payment_method_subtype), - Some(fingerprint_id), - ) - .await - .attach_printable("Unable to create Payment method data")?; - - let payment_method = db - .update_payment_method( - &(state.into()), - key_store, - payment_method, - pm_update, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to update payment method in db")?; - - let resp = pm_transforms::generate_payment_method_response(&payment_method, None)?; - - Ok(resp) - } - Err(e) => { - let pm_update = storage::PaymentMethodUpdate::StatusUpdate { - status: Some(enums::PaymentMethodStatus::Inactive), - }; - - db.update_payment_method( - &(state.into()), - key_store, - payment_method, - pm_update, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to update payment method in db")?; - - Err(e) - } - }?; - - Ok(services::ApplicationResponse::Json(response)) -} + .await?; -#[cfg(feature = "v2")] -trait PerformFilteringOnEnabledPaymentMethods { - fn perform_filtering(self) -> FilteredPaymentMethodsEnabled; -} + let response = + hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) + .perform_filtering() + .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone())) + .generate_response(customer_payment_methods.customer_payment_methods); -#[cfg(feature = "v2")] -impl PerformFilteringOnEnabledPaymentMethods - for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled -{ - fn perform_filtering(self) -> FilteredPaymentMethodsEnabled { - FilteredPaymentMethodsEnabled(self.payment_methods_enabled) - } + Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( + response, + )) } #[cfg(feature = "v2")] @@ -1262,7 +1213,10 @@ struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPa #[cfg(feature = "v2")] impl RequiredFieldsForEnabledPaymentMethodTypes { - fn generate_response(self) -> payment_methods::PaymentMethodListResponse { + fn generate_response( + self, + customer_payment_methods: Vec<payment_methods::CustomerPaymentMethod>, + ) -> payment_methods::PaymentMethodListResponse { let response_payment_methods = self .0 .into_iter() @@ -1278,121 +1232,11 @@ impl RequiredFieldsForEnabledPaymentMethodTypes { payment_methods::PaymentMethodListResponse { payment_methods_enabled: response_payment_methods, + customer_payment_methods, } } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn list_payment_methods_enabled( - state: SessionState, - merchant_account: domain::MerchantAccount, - key_store: domain::MerchantKeyStore, - profile: domain::Profile, - payment_method_id: id_type::GlobalPaymentMethodId, -) -> RouterResponse<api::PaymentMethodListResponse> { - let key_manager_state = &(&state).into(); - - let db = &*state.store; - - db.find_payment_method( - key_manager_state, - &key_store, - &payment_method_id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) - .attach_printable("Unable to find payment method")?; - - let payment_connector_accounts = db - .list_enabled_connector_accounts_by_profile_id( - key_manager_state, - profile.get_id(), - &key_store, - common_enums::ConnectorType::PaymentProcessor, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error when fetching merchant connector accounts")?; - - let response = - hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) - .perform_filtering() - .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone())) - .generate_response(); - - Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( - response, - )) -} - -#[cfg(all( - feature = "v2", - feature = "payment_methods_v2", - feature = "customer_v2" -))] -#[instrument(skip_all)] -#[allow(clippy::too_many_arguments)] -pub async fn create_payment_method_in_db( - state: &SessionState, - req: &api::PaymentMethodCreate, - customer_id: &id_type::GlobalCustomerId, - payment_method_id: id_type::GlobalPaymentMethodId, - locker_id: Option<domain::VaultId>, - merchant_id: &id_type::MerchantId, - customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, - payment_method_data: domain::types::OptionalEncryptableJsonType< - api::payment_methods::PaymentMethodsData, - >, - key_store: &domain::MerchantKeyStore, - connector_mandate_details: Option<CommonMandateReference>, - status: Option<enums::PaymentMethodStatus>, - network_transaction_id: Option<String>, - storage_scheme: enums::MerchantStorageScheme, - payment_method_billing_address: crypto::OptionalEncryptableValue, - card_scheme: Option<String>, -) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { - let db = &*state.store; - let current_time = common_utils::date_time::now(); - - let response = db - .insert_payment_method( - &state.into(), - key_store, - domain::PaymentMethod { - customer_id: customer_id.to_owned(), - merchant_id: merchant_id.to_owned(), - id: payment_method_id, - locker_id, - payment_method_type: Some(req.payment_method_type), - payment_method_subtype: Some(req.payment_method_subtype), - payment_method_data, - connector_mandate_details, - customer_acceptance, - client_secret: None, - status: status.unwrap_or(enums::PaymentMethodStatus::Active), - network_transaction_id: network_transaction_id.to_owned(), - created_at: current_time, - last_modified: current_time, - last_used_at: current_time, - payment_method_billing_address, - updated_by: None, - version: domain::consts::API_VERSION, - locker_fingerprint_id: None, - network_token_locker_id: None, - network_token_payment_method_data: None, - network_token_requestor_reference_id: None, - }, - storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - - Ok(response) -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] @@ -1404,18 +1248,11 @@ pub async fn create_payment_method_for_intent( merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, - payment_method_billing_address: crypto::OptionalEncryptableValue, -) -> errors::CustomResult<(domain::PaymentMethod, Secret<String>), errors::ApiErrorResponse> { + payment_method_billing_address: Option< + Encryptable<hyperswitch_domain_models::address::Address>, + >, +) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; - let ephemeral_key = payment_helpers::create_ephemeral_key( - state, - customer_id, - merchant_id, - ephemeral_key::ResourceType::PaymentMethod, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to create ephemeral_key")?; let current_time = common_utils::date_time::now(); @@ -1453,7 +1290,7 @@ pub async fn create_payment_method_for_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; - Ok((response, ephemeral_key.secret)) + Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1537,12 +1374,14 @@ pub async fn vault_payment_method( Ok((resp_from_vault, fingerprint_id_from_vault)) } +// TODO: check if this function will be used for listing the customer payment methods for payments +#[allow(unused)] #[cfg(all( feature = "v2", feature = "payment_methods_v2", feature = "customer_v2" ))] -async fn get_pm_list_context( +fn get_pm_list_context( payment_method_type: enums::PaymentMethod, payment_method: &domain::PaymentMethod, is_payment_associated: bool, @@ -1550,7 +1389,7 @@ async fn get_pm_list_context( let payment_method_data = payment_method .payment_method_data .clone() - .map(|payment_method_data| payment_method_data.into_inner().expose().into_inner()); + .map(|payment_method_data| payment_method_data.into_inner()); let payment_method_retrieval_context = match payment_method_data { Some(payment_methods::PaymentMethodsData::Card(card)) => { @@ -1629,316 +1468,39 @@ async fn get_pm_list_context( feature = "payment_methods_v2", feature = "customer_v2" ))] -pub async fn list_customer_payment_method_util( - state: SessionState, - merchant_account: domain::MerchantAccount, - profile: domain::Profile, - key_store: domain::MerchantKeyStore, - req: Option<api::PaymentMethodListRequest>, - customer_id: Option<id_type::GlobalCustomerId>, - is_payment_associated: bool, -) -> RouterResponse<api::CustomerPaymentMethodsListResponse> { - let limit = req.as_ref().and_then(|pml_req| pml_req.limit); - - let (customer_id, payment_intent) = if is_payment_associated { - let cloned_secret = req.and_then(|r| r.client_secret.clone()); - let payment_intent = payment_helpers::verify_payment_intent_time_and_client_secret( - &state, - &merchant_account, - &key_store, - cloned_secret, - ) - .await?; - - ( - payment_intent - .as_ref() - .and_then(|pi| pi.customer_id.clone()), - payment_intent, - ) - } else { - (customer_id, None) - }; - - let resp = if let Some(cust) = customer_id { - Box::pin(list_customer_payment_method( - &state, - &merchant_account, - profile, - key_store, - payment_intent, - &cust, - limit, - is_payment_associated, - )) - .await? - } else { - let response = api::CustomerPaymentMethodsListResponse { - customer_payment_methods: Vec::new(), - is_guest_customer: Some(true), - }; - services::ApplicationResponse::Json(response) - }; - - Ok(resp) -} - -#[allow(clippy::too_many_arguments)] -#[cfg(all( - feature = "v2", - feature = "payment_methods_v2", - feature = "customer_v2" -))] -pub async fn list_customer_payment_method( +pub async fn list_customer_payment_method_core( state: &SessionState, merchant_account: &domain::MerchantAccount, - profile: domain::Profile, - key_store: domain::MerchantKeyStore, - payment_intent: Option<PaymentIntent>, + key_store: &domain::MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, - limit: Option<i64>, - is_payment_associated: bool, -) -> RouterResponse<api::CustomerPaymentMethodsListResponse> { +) -> RouterResult<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; let key_manager_state = &(state).into(); - let customer = db - .find_customer_by_global_id( - key_manager_state, - customer_id, - merchant_account.get_id(), - &key_store, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - - let payments_info = payment_intent - .async_map(|pi| { - pm_types::SavedPMLPaymentsInfo::form_payments_info( - pi, - merchant_account, - profile, - db, - key_manager_state, - &key_store, - ) - }) - .await - .transpose()?; - let saved_payment_methods = db .find_payment_method_by_global_customer_id_merchant_id_status( key_manager_state, - &key_store, + key_store, customer_id, merchant_account.get_id(), common_enums::PaymentMethodStatus::Active, - limit, + None, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let mut filtered_saved_payment_methods_ctx = Vec::new(); - for payment_method in saved_payment_methods.into_iter() { - let payment_method_type = payment_method - .get_payment_method_type() - .get_required_value("payment_method")?; - let parent_payment_method_token = - is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token")); - - let pm_list_context = - get_pm_list_context(payment_method_type, &payment_method, is_payment_associated) - .await?; - - if let Some(ctx) = pm_list_context { - filtered_saved_payment_methods_ctx.push(( - ctx, - parent_payment_method_token, - payment_method, - )); - } - } - - let merchant_connector_accounts = if filtered_saved_payment_methods_ctx.iter().any( - |(_pm_list_context, _parent_payment_method_token, pm)| { - pm.connector_mandate_details.is_some() - }, - ) { - db.find_merchant_connector_account_by_merchant_id_and_disabled_list( - key_manager_state, - merchant_account.get_id(), - true, - &key_store, - ) - .await - .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)? - } else { - Vec::new() - }; - let merchant_connector_accounts = - domain::MerchantConnectorAccounts::new(merchant_connector_accounts); - - let pm_list_futures = filtered_saved_payment_methods_ctx + let customer_payment_methods = saved_payment_methods .into_iter() - .map(|ctx| { - generate_saved_pm_response( - state, - &key_store, - merchant_account, - &merchant_connector_accounts, - ctx, - &customer, - payments_info.as_ref(), - ) - }) - .collect::<Vec<_>>(); - - let customer_pms = futures::future::join_all(pm_list_futures) - .await - .into_iter() - .collect::<Result<Vec<_>, _>>() - .attach_printable("Failed to obtain customer payment methods")?; - - let mut response = api::CustomerPaymentMethodsListResponse { - customer_payment_methods: customer_pms, - is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent - }; - - /* - TODO: Implement surcharge for v2 - if is_payment_associated { - Box::pin(cards::perform_surcharge_ops( - payments_info.as_ref().map(|pi| pi.payment_intent.clone()), - state, - merchant_account, - key_store, - payments_info.map(|pi| pi.profile), - &mut response, - )) - .await?; - } - */ - - Ok(services::ApplicationResponse::Json(response)) -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -async fn generate_saved_pm_response( - state: &SessionState, - key_store: &domain::MerchantKeyStore, - merchant_account: &domain::MerchantAccount, - merchant_connector_accounts: &domain::MerchantConnectorAccounts, - (pm_list_context, parent_payment_method_token, pm): ( - PaymentMethodListContext, - Option<String>, - domain::PaymentMethod, - ), - customer: &domain::Customer, - payment_info: Option<&pm_types::SavedPMLPaymentsInfo>, -) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> { - let payment_method_type = pm - .get_payment_method_type() - .get_required_value("payment_method_type")?; - - let bank_details = if payment_method_type == enums::PaymentMethod::BankDebit { - cards::get_masked_bank_details(&pm) - .await - .unwrap_or_else(|err| { - logger::error!(error=?err); - None - }) - } else { - None - }; - - let payment_method_billing = pm - .payment_method_billing_address - .clone() - .map(|decrypted_data| decrypted_data.into_inner().expose()) - .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address")) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to parse payment method billing address details")?; - - let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) = - payment_info - .map(|pi| { - ( - pi.is_connector_agnostic_mit_enabled, - pi.collect_cvv_during_payment, - pi.off_session_payment_flag, - Some(pi.profile.get_id().to_owned()), - ) - }) - .unwrap_or((false, false, false, Default::default())); - - let mca_enabled = cards::get_mca_status( - state, - key_store, - profile_id, - merchant_account.get_id(), - is_connector_agnostic_mit_enabled, - pm.connector_mandate_details.as_ref(), - pm.network_transaction_id.as_ref(), - merchant_connector_accounts, - ) - .await; - - let requires_cvv = if is_connector_agnostic_mit_enabled { - requires_cvv - && !(off_session_payment_flag - && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some())) - } else { - requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some()) - }; - - let pmd = match &pm_list_context { - PaymentMethodListContext::Card { card_details, .. } => { - Some(api::PaymentMethodListData::Card(card_details.clone())) - } - #[cfg(feature = "payouts")] - PaymentMethodListContext::BankTransfer { - bank_transfer_details, - .. - } => Some(api::PaymentMethodListData::Bank( - bank_transfer_details.clone(), - )), - PaymentMethodListContext::Bank { .. } | PaymentMethodListContext::TemporaryToken { .. } => { - None - } - }; + .map(ForeignTryFrom::foreign_try_from) + .collect::<Result<Vec<api::CustomerPaymentMethod>, _>>() + .change_context(errors::ApiErrorResponse::InternalServerError)?; - let pma = api::CustomerPaymentMethod { - payment_token: parent_payment_method_token.clone(), - payment_method_id: pm.get_id().get_string_repr().to_owned(), - customer_id: pm.customer_id.to_owned(), - payment_method_type, - payment_method_subtype: pm.get_payment_method_subtype(), - payment_method_data: pmd, - recurring_enabled: mca_enabled, - created: pm.created_at, - bank: bank_details, - surcharge_details: None, - requires_cvv: requires_cvv - && !(off_session_payment_flag && pm.connector_mandate_details.is_some()), - last_used_at: Some(pm.last_used_at), - is_default: customer - .default_payment_method_id - .as_ref() - .is_some_and(|payment_method_id| payment_method_id == pm.get_id().get_string_repr()), - billing: payment_method_billing, + let response = api::CustomerPaymentMethodsListResponse { + customer_payment_methods, }; - payment_info - .async_map(|pi| { - pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context) - }) - .await - .transpose()?; - - Ok(pma) + Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1972,7 +1534,7 @@ pub async fn retrieve_payment_method( let pmd = payment_method .payment_method_data .clone() - .map(|x| x.into_inner().expose().into_inner()) + .map(|x| x.into_inner()) .and_then(|pmd| match pmd { api::PaymentMethodsData::Card(card) => { Some(api::PaymentMethodResponseData::Card(card.into())) @@ -1989,7 +1551,6 @@ pub async fn retrieve_payment_method( created: Some(payment_method.created_at), recurring_enabled: false, last_used_at: Some(payment_method.last_used_at), - ephemeral_key: None, payment_method_data: pmd, }; @@ -2001,21 +1562,33 @@ pub async fn retrieve_payment_method( pub async fn update_payment_method( state: SessionState, merchant_account: domain::MerchantAccount, - req: api::PaymentMethodUpdate, - payment_method_id: &str, key_store: domain::MerchantKeyStore, + req: api::PaymentMethodUpdate, + payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResponse<api::PaymentMethodResponse> { - let db = state.store.as_ref(); + let response = + update_payment_method_core(state, merchant_account, key_store, req, payment_method_id) + .await?; - let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(payment_method_id.to_string()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to generate GlobalPaymentMethodId")?; + Ok(services::ApplicationResponse::Json(response)) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn update_payment_method_core( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + req: api::PaymentMethodUpdate, + payment_method_id: &id_type::GlobalPaymentMethodId, +) -> RouterResult<api::PaymentMethodResponse> { + let db = state.store.as_ref(); let payment_method = db .find_payment_method( &((&state).into()), &key_store, - &pm_id, + payment_method_id, merchant_account.storage_scheme, ) .await @@ -2076,11 +1649,11 @@ pub async fn update_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let response = pm_transforms::generate_payment_method_response(&payment_method, None)?; + let response = pm_transforms::generate_payment_method_response(&payment_method)?; // Add a PT task to handle payment_method delete from vault - Ok(services::ApplicationResponse::Json(response)) + Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -2135,6 +1708,7 @@ pub async fn delete_payment_method( let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(enums::PaymentMethodStatus::Inactive), }; + db.update_payment_method( &((&state).into()), &key_store, @@ -2156,6 +1730,216 @@ pub async fn delete_payment_method( Ok(services::ApplicationResponse::Json(response)) } +#[cfg(feature = "v2")] +#[async_trait::async_trait] +trait EncryptableData { + type Output; + async fn encrypt_data( + &self, + key_manager_state: &common_utils::types::keymanager::KeyManagerState, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<Self::Output>; +} + +#[cfg(feature = "v2")] +#[async_trait::async_trait] +impl EncryptableData for payment_methods::PaymentMethodSessionRequest { + type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodsSession; + + async fn encrypt_data( + &self, + key_manager_state: &common_utils::types::keymanager::KeyManagerState, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<Self::Output> { + use common_utils::types::keymanager::ToEncryptable; + + let encrypted_billing_address = self + .billing + .clone() + .map(|address| address.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode billing address")? + .map(Secret::new); + + let batch_encrypted_data = domain_types::crypto_operation( + key_manager_state, + common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodsSession), + domain_types::CryptoOperation::BatchEncrypt( + hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodsSession::to_encryptable( + hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodsSession { + billing: encrypted_billing_address, + }, + ), + ), + common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting payment methods session details".to_string())?; + + let encrypted_data = + hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodsSession::from_encryptable( + batch_encrypted_data, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting payment methods session detailss")?; + + Ok(encrypted_data) + } +} + +#[cfg(feature = "v2")] +pub async fn payment_methods_session_create( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + request: payment_methods::PaymentMethodSessionRequest, +) -> RouterResponse<payment_methods::PaymentMethodsSessionResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + db.find_customer_by_global_id( + key_manager_state, + &request.customer_id, + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + + let payment_methods_session_id = + id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to generate GlobalPaymentMethodSessionId")?; + + let encrypted_data = request + .encrypt_data(key_manager_state, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt payment methods session data")?; + + let billing = encrypted_data + .billing + .as_ref() + .map(|data| { + data.clone() + .deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to decode billing address")?; + + // If not passed in the request, use the default value from constants + let expires_in = request + .expires_in + .unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY) + .into(); + + let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in)); + + let client_secret = payment_helpers::create_client_secret( + &state, + merchant_account.get_id(), + util_types::authentication::ResourceId::PaymentMethodSession( + payment_methods_session_id.clone(), + ), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + + let payment_method_session_domain_model = + hyperswitch_domain_models::payment_methods::PaymentMethodsSession { + id: payment_methods_session_id, + customer_id: request.customer_id, + billing, + psp_tokenization: request.psp_tokenization, + network_tokenization: request.network_tokenization, + expires_at, + }; + + db.insert_payment_methods_session( + key_manager_state, + &key_store, + payment_method_session_domain_model.clone(), + expires_in, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to insert payment methods session in db")?; + + let response = payment_methods::PaymentMethodsSessionResponse::foreign_from(( + payment_method_session_domain_model, + client_secret.secret, + )); + + Ok(services::ApplicationResponse::Json(response)) +} + +#[cfg(feature = "v2")] +pub async fn payment_methods_session_retrieve( + state: SessionState, + _merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, +) -> RouterResponse<payment_methods::PaymentMethodsSessionResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let payment_method_session_domain_model = db + .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment methods session does not exist or has expired".to_string(), + }) + .attach_printable("Failed to retrieve payment methods session from db")?; + + let response = payment_methods::PaymentMethodsSessionResponse::foreign_from(( + payment_method_session_domain_model, + Secret::new("CLIENT_SECRET_REDACTED".to_string()), + )); + + Ok(services::ApplicationResponse::Json(response)) +} + +#[cfg(feature = "v2")] +pub async fn payment_methods_session_update_payment_method( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, + request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, +) -> RouterResponse<payment_methods::PaymentMethodResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + // Validate if the session still exists + db.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment methods session does not exist or has expired".to_string(), + }) + .attach_printable("Failed to retrieve payment methods session from db")?; + + let payment_method_update_request = request.payment_method_update_request; + + let updated_payment_method = update_payment_method_core( + state, + merchant_account, + key_store, + payment_method_update_request, + &request.payment_method_id, + ) + .await + .attach_printable("Failed to update saved payment method")?; + + Ok(services::ApplicationResponse::Json(updated_payment_method)) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl pm_types::SavedPMLPaymentsInfo { pub async fn form_payments_info( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 1f4fb6904fd..1f37cc157e4 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -63,6 +63,7 @@ use strum::IntoEnumIterator; not(feature = "payment_methods_v2") ))] use super::migration; +#[cfg(feature = "v1")] use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, @@ -5434,10 +5435,7 @@ pub async fn get_masked_bank_details( .transpose()?; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] - let payment_method_data = pm - .payment_method_data - .clone() - .map(|x| x.into_inner().expose().into_inner()); + let payment_method_data = pm.payment_method_data.clone().map(|x| x.into_inner()); match payment_method_data { Some(pmd) => match pmd { diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs index 6a2b3198e93..7c8558ff8ca 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -367,82 +367,83 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( Ok(surcharge_metadata) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub async fn perform_surcharge_decision_management_for_saved_cards( - state: &SessionState, - algorithm_ref: routing::RoutingAlgorithmRef, - payment_attempt: &storage::PaymentAttempt, - payment_intent: &storage::PaymentIntent, - customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod], -) -> ConditionalConfigResult<types::SurchargeMetadata> { - // let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.id.clone()); - let mut surcharge_metadata = todo!(); - - let surcharge_source = match ( - payment_attempt.get_surcharge_details(), - algorithm_ref.surcharge_config_algo_id, - ) { - (Some(request_surcharge_details), _) => { - SurchargeSource::Predetermined(request_surcharge_details) - } - (None, Some(algorithm_id)) => { - let cached_algo = ensure_algorithm_cached( - &*state.store, - &payment_attempt.merchant_id, - algorithm_id.as_str(), - ) - .await?; - - SurchargeSource::Generate(cached_algo) - } - (None, None) => return Ok(surcharge_metadata), - }; - let surcharge_source_log_message = match &surcharge_source { - SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", - SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", - }; - logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message); - let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None) - .change_context(ConfigError::InputConstructionError)?; - - for customer_payment_method in customer_payment_method_list.iter_mut() { - let payment_token = customer_payment_method - .payment_token - .clone() - .get_required_value("payment_token") - .change_context(ConfigError::InputConstructionError)?; - - backend_input.payment_method.payment_method = - Some(customer_payment_method.payment_method_type); - backend_input.payment_method.payment_method_type = - customer_payment_method.payment_method_subtype; - - let card_network = match customer_payment_method.payment_method_data.as_ref() { - Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => { - card.card_network.clone() - } - _ => None, - }; - backend_input.payment_method.card_network = card_network; - - let surcharge_details = surcharge_source - .generate_surcharge_details_and_populate_surcharge_metadata( - &backend_input, - payment_attempt, - ( - &mut surcharge_metadata, - types::SurchargeKey::Token(payment_token), - ), - )?; - customer_payment_method.surcharge_details = surcharge_details - .map(|surcharge_details| { - SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt)) - .change_context(ConfigError::DslParsingError) - }) - .transpose()?; - } - Ok(surcharge_metadata) -} +// TODO: uncomment and resolve compiler error when required +// #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +// pub async fn perform_surcharge_decision_management_for_saved_cards( +// state: &SessionState, +// algorithm_ref: routing::RoutingAlgorithmRef, +// payment_attempt: &storage::PaymentAttempt, +// payment_intent: &storage::PaymentIntent, +// customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod], +// ) -> ConditionalConfigResult<types::SurchargeMetadata> { +// // let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.id.clone()); +// let mut surcharge_metadata = todo!(); + +// let surcharge_source = match ( +// payment_attempt.get_surcharge_details(), +// algorithm_ref.surcharge_config_algo_id, +// ) { +// (Some(request_surcharge_details), _) => { +// SurchargeSource::Predetermined(request_surcharge_details) +// } +// (None, Some(algorithm_id)) => { +// let cached_algo = ensure_algorithm_cached( +// &*state.store, +// &payment_attempt.merchant_id, +// algorithm_id.as_str(), +// ) +// .await?; + +// SurchargeSource::Generate(cached_algo) +// } +// (None, None) => return Ok(surcharge_metadata), +// }; +// let surcharge_source_log_message = match &surcharge_source { +// SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", +// SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", +// }; +// logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message); +// let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None) +// .change_context(ConfigError::InputConstructionError)?; + +// for customer_payment_method in customer_payment_method_list.iter_mut() { +// let payment_token = customer_payment_method +// .payment_token +// .clone() +// .get_required_value("payment_token") +// .change_context(ConfigError::InputConstructionError)?; + +// backend_input.payment_method.payment_method = +// Some(customer_payment_method.payment_method_type); +// backend_input.payment_method.payment_method_type = +// customer_payment_method.payment_method_subtype; + +// let card_network = match customer_payment_method.payment_method_data.as_ref() { +// Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => { +// card.card_network.clone() +// } +// _ => None, +// }; +// backend_input.payment_method.card_network = card_network; + +// let surcharge_details = surcharge_source +// .generate_surcharge_details_and_populate_surcharge_metadata( +// &backend_input, +// payment_attempt, +// ( +// &mut surcharge_metadata, +// types::SurchargeKey::Token(payment_token), +// ), +// )?; +// customer_payment_method.surcharge_details = surcharge_details +// .map(|surcharge_details| { +// SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt)) +// .change_context(ConfigError::DslParsingError) +// }) +// .transpose()?; +// } +// Ok(surcharge_metadata) +// } #[cfg(feature = "v2")] fn get_surcharge_details_from_surcharge_output( diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 4a43eef1ed6..c4d3eafe463 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -16,7 +16,7 @@ use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::types::payment_methods as pm_types; +use crate::types::{payment_methods as pm_types, transformers}; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -551,12 +551,11 @@ pub fn generate_pm_vaulting_req_from_update_request( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_payment_method_response( pm: &domain::PaymentMethod, - ephemeral_key: Option<Secret<String>>, ) -> errors::RouterResult<api::PaymentMethodResponse> { let pmd = pm .payment_method_data .clone() - .map(|data| data.into_inner().expose().into_inner()) + .map(|data| data.into_inner()) .and_then(|data| match data { api::PaymentMethodsData::Card(card) => { Some(api::PaymentMethodResponseData::Card(card.into())) @@ -573,7 +572,6 @@ pub fn generate_payment_method_response( created: Some(pm.created_at), recurring_enabled: false, last_used_at: Some(pm.last_used_at), - ephemeral_key, payment_method_data: pmd, }; @@ -911,3 +909,93 @@ pub fn mk_card_value2( .change_context(errors::VaultError::FetchCardFailed)?; Ok(value2_req) } + +#[cfg(feature = "v2")] +impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymentMethod { + type Error = error_stack::Report<errors::ValidationError>; + + fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> { + // For payment methods that are active we should always have the payment method subtype + let payment_method_subtype = + item.payment_method_subtype + .ok_or(errors::ValidationError::MissingRequiredField { + field_name: "payment_method_subtype".to_string(), + })?; + + // For payment methods that are active we should always have the payment method type + let payment_method_type = + item.payment_method_type + .ok_or(errors::ValidationError::MissingRequiredField { + field_name: "payment_method_type".to_string(), + })?; + + let payment_method_data = item + .payment_method_data + .map(|payment_method_data| payment_method_data.into_inner()) + .map(|payment_method_data| match payment_method_data { + api_models::payment_methods::PaymentMethodsData::Card( + card_details_payment_method, + ) => { + let card_details = api::CardDetailFromLocker::from(card_details_payment_method); + api_models::payment_methods::PaymentMethodListData::Card(card_details) + } + api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(), + api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => { + todo!() + } + }); + + let payment_method_billing = item + .payment_method_billing_address + .clone() + .map(|billing| billing.into_inner()) + .map(From::from); + + // TODO: check how we can get this field + let recurring_enabled = true; + + Ok(Self { + id: item.id, + customer_id: item.customer_id, + payment_method_type, + payment_method_subtype, + created: item.created_at, + last_used_at: item.last_used_at, + recurring_enabled, + payment_method_data, + bank: None, + requires_cvv: true, + is_default: false, + billing: payment_method_billing, + }) + } +} + +#[cfg(feature = "v2")] +impl + transformers::ForeignFrom<( + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + Secret<String>, + )> for api_models::payment_methods::PaymentMethodsSessionResponse +{ + fn foreign_from( + item: ( + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + Secret<String>, + ), + ) -> Self { + let (session, client_secret) = item; + Self { + id: session.id, + customer_id: session.customer_id, + billing: session + .billing + .map(|address| address.into_inner()) + .map(From::from), + psp_tokenization: session.psp_tokenization, + network_tokenization: session.network_tokenization, + expires_at: session.expires_at, + client_secret, + } + } +} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index cfa57a35654..28d843e2350 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, collections::HashSet, str::FromStr}; #[cfg(feature = "v2")] -use api_models::ephemeral_key::EphemeralKeyResponse; +use api_models::ephemeral_key::ClientSecretResponse; use api_models::{ mandates::RecurringDetails, payments::{additional_info as payment_additional_types, RequestSurchargeDetails}, @@ -3055,76 +3055,70 @@ pub async fn make_ephemeral_key( } #[cfg(feature = "v2")] -pub async fn make_ephemeral_key( +pub async fn make_client_secret( state: SessionState, - customer_id: id_type::GlobalCustomerId, + resource_id: api_models::ephemeral_key::ResourceId, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, headers: &actix_web::http::header::HeaderMap, -) -> errors::RouterResponse<EphemeralKeyResponse> { +) -> errors::RouterResponse<ClientSecretResponse> { let db = &state.store; let key_manager_state = &((&state).into()); - db.find_customer_by_global_id( - key_manager_state, - &customer_id, - merchant_account.get_id(), - &key_store, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - - let resource_type = services::authentication::get_header_value_by_key( - headers::X_RESOURCE_TYPE.to_string(), - headers, - )? - .map(ephemeral_key::ResourceType::from_str) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: format!("`{}` header is invalid", headers::X_RESOURCE_TYPE), - })? - .get_required_value("ResourceType") - .attach_printable("Failed to convert ResourceType from string")?; - - let ephemeral_key = create_ephemeral_key( - &state, - &customer_id, - merchant_account.get_id(), - resource_type, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to create ephemeral key")?; - let response = EphemeralKeyResponse::foreign_from(ephemeral_key); + match &resource_id { + api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { + db.find_customer_by_global_id( + key_manager_state, + global_customer_id, + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + } + } + + let resource_id = match resource_id { + api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { + common_utils::types::authentication::ResourceId::Customer(global_customer_id) + } + }; + + let client_secret = create_client_secret(&state, merchant_account.get_id(), resource_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + + let response = ClientSecretResponse::foreign_try_from(client_secret) + .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] -pub async fn create_ephemeral_key( +pub async fn create_client_secret( state: &SessionState, - customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, - resource_type: ephemeral_key::ResourceType, -) -> RouterResult<ephemeral_key::EphemeralKeyType> { + resource_id: common_utils::types::authentication::ResourceId, +) -> RouterResult<ephemeral_key::ClientSecretType> { use common_utils::generate_time_ordered_id; let store = &state.store; - let id = id_type::EphemeralKeyId::generate(); - let secret = masking::Secret::new(generate_time_ordered_id("epk")); - let ephemeral_key = ephemeral_key::EphemeralKeyTypeNew { + let id = id_type::ClientSecretId::generate(); + let secret = masking::Secret::new(generate_time_ordered_id("cs")); + + let client_secret = ephemeral_key::ClientSecretTypeNew { id, - customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), secret, - resource_type, + resource_id, }; - let ephemeral_key = store - .create_ephemeral_key(ephemeral_key, state.conf.eph_key.validity) + let client_secret = store + .create_client_secret(client_secret, state.conf.eph_key.validity) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to create ephemeral key")?; - Ok(ephemeral_key) + .attach_printable("Unable to create client secret")?; + Ok(client_secret) } #[cfg(feature = "v1")] @@ -3142,13 +3136,13 @@ pub async fn delete_ephemeral_key( } #[cfg(feature = "v2")] -pub async fn delete_ephemeral_key( +pub async fn delete_client_secret( state: SessionState, ephemeral_key_id: String, -) -> errors::RouterResponse<EphemeralKeyResponse> { +) -> errors::RouterResponse<ClientSecretResponse> { let db = state.store.as_ref(); let ephemeral_key = db - .delete_ephemeral_key(&ephemeral_key_id) + .delete_client_secret(&ephemeral_key_id) .await .map_err(|err| match err.current_context() { errors::StorageError::ValueNotFound(_) => { @@ -3160,7 +3154,8 @@ pub async fn delete_ephemeral_key( }) .attach_printable("Unable to delete ephemeral key")?; - let response = EphemeralKeyResponse::foreign_from(ephemeral_key); + let response = ClientSecretResponse::foreign_try_from(ephemeral_key) + .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5371afca931..1f6e03a0dec 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1929,7 +1929,7 @@ pub fn payments_to_payments_response<Op, F: Clone, D>( _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, -) -> RouterResponse<api::PaymentsResponse> +) -> RouterResponse<api_models::payments::PaymentsRetrieveResponse> where Op: Debug, D: OperationSessionGetters<F>, @@ -2751,6 +2751,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay } } +#[cfg(feature = "v1")] impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse { fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self { Self { diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 9b6396013f4..a08f80354bf 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -2,11 +2,9 @@ //! //! Functions that are used to perform the retrieval of merchant's //! routing dict, configs, defaults -use std::fmt::Debug; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::str::FromStr; -#[cfg(any(feature = "dynamic_routing", feature = "v1"))] -use std::sync::Arc; +use std::{fmt::Debug, sync::Arc}; use api_models::routing as routing_types; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index d852319e388..17da4902bac 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -30,6 +30,7 @@ pub mod merchant_key_store; pub mod organization; pub mod payment_link; pub mod payment_method; +pub mod payment_method_session; pub mod refund; pub mod relay; pub mod reverse_lookup; @@ -40,6 +41,7 @@ pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; + use common_utils::id_type; use diesel_models::{ fraud_check::{FraudCheck, FraudCheckUpdate}, @@ -97,6 +99,7 @@ pub trait StorageInterface: + dashboard_metadata::DashboardMetadataInterface + dispute::DisputeInterface + ephemeral_key::EphemeralKeyInterface + + ephemeral_key::ClientSecretInterface + events::EventInterface + file::FileMetadataInterface + FraudCheckInterface @@ -135,6 +138,7 @@ pub trait StorageInterface: + generic_link::GenericLinkInterface + relay::RelayInterface + user::theme::ThemeInterface + + payment_method_session::PaymentMethodsSessionInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index b3e33cd777f..2799d1c9ccb 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -3,7 +3,7 @@ use common_utils::id_type; use time::ext::NumericalDuration; #[cfg(feature = "v2")] -use crate::types::storage::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew, ResourceType}; +use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, db::MockDb, @@ -19,36 +19,39 @@ pub trait EphemeralKeyInterface { _validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError>; - #[cfg(feature = "v2")] - async fn create_ephemeral_key( - &self, - _ek: EphemeralKeyTypeNew, - _validity: i64, - ) -> CustomResult<EphemeralKeyType, errors::StorageError>; - #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, _key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; - #[cfg(feature = "v2")] - async fn get_ephemeral_key( - &self, - _key: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError>; - #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, _id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; +} +#[async_trait::async_trait] +pub trait ClientSecretInterface { #[cfg(feature = "v2")] - async fn delete_ephemeral_key( + async fn create_client_secret( + &self, + _ek: ClientSecretTypeNew, + _validity: i64, + ) -> CustomResult<ClientSecretType, errors::StorageError>; + + #[cfg(feature = "v2")] + async fn get_client_secret( + &self, + _key: &str, + ) -> CustomResult<ClientSecretType, errors::StorageError>; + + #[cfg(feature = "v2")] + async fn delete_client_secret( &self, _id: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError>; + ) -> CustomResult<ClientSecretType, errors::StorageError>; } mod storage { @@ -65,11 +68,9 @@ mod storage { use storage_impl::redis::kv_store::RedisConnInterface; use time::ext::NumericalDuration; - use super::EphemeralKeyInterface; + use super::{ClientSecretInterface, EphemeralKeyInterface}; #[cfg(feature = "v2")] - use crate::types::storage::ephemeral_key::{ - EphemeralKeyType, EphemeralKeyTypeNew, ResourceType, - }; + use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, services::Store, @@ -137,37 +138,74 @@ mod storage { } } + #[cfg(feature = "v1")] + #[instrument(skip_all)] + async fn get_ephemeral_key( + &self, + key: &str, + ) -> CustomResult<EphemeralKey, errors::StorageError> { + let key = format!("epkey_{key}"); + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey") + .await + .change_context(errors::StorageError::KVError) + } + + #[cfg(feature = "v1")] + async fn delete_ephemeral_key( + &self, + id: &str, + ) -> CustomResult<EphemeralKey, errors::StorageError> { + let ek = self.get_ephemeral_key(id).await?; + + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .delete_key(&format!("epkey_{}", &ek.id).into()) + .await + .change_context(errors::StorageError::KVError)?; + + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .delete_key(&format!("epkey_{}", &ek.secret).into()) + .await + .change_context(errors::StorageError::KVError)?; + Ok(ek) + } + } + + #[async_trait::async_trait] + impl ClientSecretInterface for Store { #[cfg(feature = "v2")] #[instrument(skip_all)] - async fn create_ephemeral_key( + async fn create_client_secret( &self, - new: EphemeralKeyTypeNew, + new: ClientSecretTypeNew, validity: i64, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + ) -> CustomResult<ClientSecretType, errors::StorageError> { let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); let id_key = new.id.generate_redis_key(); - let created_ephemeral_key = EphemeralKeyType { + let created_client_secret = ClientSecretType { id: new.id, created_at, expires, - customer_id: new.customer_id, merchant_id: new.merchant_id, secret: new.secret, - resource_type: new.resource_type, + resource_id: new.resource_id, }; - let secret_key = created_ephemeral_key.generate_secret_key(); + let secret_key = created_client_secret.generate_secret_key(); match self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ - (&secret_key.as_str().into(), &created_ephemeral_key), - (&id_key.as_str().into(), &created_ephemeral_key), + (&secret_key.as_str().into(), &created_client_secret), + (&id_key.as_str().into(), &created_client_secret), ], - "ephkey", + "csh", None, ) .await @@ -191,69 +229,34 @@ mod storage { .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; - Ok(created_ephemeral_key) + Ok(created_client_secret) } Err(er) => Err(er).change_context(errors::StorageError::KVError), } } - #[cfg(feature = "v1")] - #[instrument(skip_all)] - async fn get_ephemeral_key( - &self, - key: &str, - ) -> CustomResult<EphemeralKey, errors::StorageError> { - let key = format!("epkey_{key}"); - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey") - .await - .change_context(errors::StorageError::KVError) - } - #[cfg(feature = "v2")] #[instrument(skip_all)] - async fn get_ephemeral_key( + async fn get_client_secret( &self, key: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - let key = format!("epkey_{key}"); + ) -> CustomResult<ClientSecretType, errors::StorageError> { + let key = format!("cs_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKeyType") + .get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType") .await .change_context(errors::StorageError::KVError) } - #[cfg(feature = "v1")] - async fn delete_ephemeral_key( - &self, - id: &str, - ) -> CustomResult<EphemeralKey, errors::StorageError> { - let ek = self.get_ephemeral_key(id).await?; - - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .delete_key(&format!("epkey_{}", &ek.id).into()) - .await - .change_context(errors::StorageError::KVError)?; - - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .delete_key(&format!("epkey_{}", &ek.secret).into()) - .await - .change_context(errors::StorageError::KVError)?; - Ok(ek) - } - #[cfg(feature = "v2")] - async fn delete_ephemeral_key( + async fn delete_client_secret( &self, id: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - let ephemeral_key = self.get_ephemeral_key(id).await?; - let redis_id_key = ephemeral_key.id.generate_redis_key(); - let secret_key = ephemeral_key.generate_secret_key(); + ) -> CustomResult<ClientSecretType, errors::StorageError> { + let client_secret = self.get_client_secret(id).await?; + let redis_id_key = client_secret.id.generate_redis_key(); + let secret_key = client_secret.generate_secret_key(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? @@ -276,7 +279,7 @@ mod storage { } _ => err.change_context(errors::StorageError::KVError), })?; - Ok(ephemeral_key) + Ok(client_secret) } } } @@ -305,15 +308,6 @@ impl EphemeralKeyInterface for MockDb { Ok(ephemeral_key) } - #[cfg(feature = "v2")] - async fn create_ephemeral_key( - &self, - ek: EphemeralKeyTypeNew, - validity: i64, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - todo!() - } - #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, @@ -333,14 +327,6 @@ impl EphemeralKeyInterface for MockDb { } } - #[cfg(feature = "v2")] - async fn get_ephemeral_key( - &self, - key: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - todo!() - } - #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, @@ -356,12 +342,32 @@ impl EphemeralKeyInterface for MockDb { ); } } +} +#[async_trait::async_trait] +impl ClientSecretInterface for MockDb { #[cfg(feature = "v2")] - async fn delete_ephemeral_key( + async fn create_client_secret( + &self, + new: ClientSecretTypeNew, + validity: i64, + ) -> CustomResult<ClientSecretType, errors::StorageError> { + todo!() + } + + #[cfg(feature = "v2")] + async fn get_client_secret( + &self, + key: &str, + ) -> CustomResult<ClientSecretType, errors::StorageError> { + todo!() + } + + #[cfg(feature = "v2")] + async fn delete_client_secret( &self, id: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 3622695c9f2..2dc7191863a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -7,7 +7,7 @@ use common_utils::{ types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; #[cfg(feature = "v2")] -use diesel_models::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew}; +use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use diesel_models::{ enums, enums::ProcessTrackerStatus, @@ -39,6 +39,7 @@ use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, + ephemeral_key::ClientSecretInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, @@ -50,6 +51,7 @@ use crate::services::kafka::payout::KafkaPayout; use crate::{ core::errors::{self, ProcessTrackerError}, db::{ + self, address::AddressInterface, api_keys::ApiKeyInterface, authentication::AuthenticationInterface, @@ -658,15 +660,6 @@ impl EphemeralKeyInterface for KafkaStore { self.diesel_store.create_ephemeral_key(ek, validity).await } - #[cfg(feature = "v2")] - async fn create_ephemeral_key( - &self, - ek: EphemeralKeyTypeNew, - validity: i64, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - self.diesel_store.create_ephemeral_key(ek, validity).await - } - #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, @@ -675,14 +668,6 @@ impl EphemeralKeyInterface for KafkaStore { self.diesel_store.get_ephemeral_key(key).await } - #[cfg(feature = "v2")] - async fn get_ephemeral_key( - &self, - key: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - self.diesel_store.get_ephemeral_key(key).await - } - #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, @@ -690,13 +675,33 @@ impl EphemeralKeyInterface for KafkaStore { ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.delete_ephemeral_key(id).await } +} +#[async_trait::async_trait] +impl ClientSecretInterface for KafkaStore { #[cfg(feature = "v2")] - async fn delete_ephemeral_key( + async fn create_client_secret( + &self, + ek: ClientSecretTypeNew, + validity: i64, + ) -> CustomResult<ClientSecretType, errors::StorageError> { + self.diesel_store.create_client_secret(ek, validity).await + } + + #[cfg(feature = "v2")] + async fn get_client_secret( + &self, + key: &str, + ) -> CustomResult<ClientSecretType, errors::StorageError> { + self.diesel_store.get_client_secret(key).await + } + + #[cfg(feature = "v2")] + async fn delete_client_secret( &self, id: &str, - ) -> CustomResult<EphemeralKeyType, errors::StorageError> { - self.diesel_store.delete_ephemeral_key(id).await + ) -> CustomResult<ClientSecretType, errors::StorageError> { + self.diesel_store.delete_client_secret(id).await } } @@ -3922,6 +3927,40 @@ impl ThemeInterface for KafkaStore { } } +#[async_trait::async_trait] +#[cfg(feature = "v2")] +impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore { + async fn insert_payment_methods_session( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + validity: i64, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .insert_payment_methods_session(state, key_store, payment_methods_session, validity) + .await + } + + async fn get_payment_methods_session( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + id: &id_type::GlobalPaymentMethodSessionId, + ) -> CustomResult< + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + errors::StorageError, + > { + self.diesel_store + .get_payment_methods_session(state, key_store, id) + .await + } +} + +#[async_trait::async_trait] +#[cfg(feature = "v1")] +impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore {} + #[async_trait::async_trait] impl CallbackMapperInterface for KafkaStore { #[instrument(skip_all)] diff --git a/crates/router/src/db/payment_method_session.rs b/crates/router/src/db/payment_method_session.rs new file mode 100644 index 00000000000..a7e500ac52c --- /dev/null +++ b/crates/router/src/db/payment_method_session.rs @@ -0,0 +1,137 @@ +#[cfg(feature = "v2")] +use crate::core::errors::{self, CustomResult}; +use crate::db::MockDb; + +#[cfg(feature = "v2")] +#[async_trait::async_trait] +pub trait PaymentMethodsSessionInterface { + async fn insert_payment_methods_session( + &self, + state: &common_utils::types::keymanager::KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + validity: i64, + ) -> CustomResult<(), errors::StorageError>; + + async fn get_payment_methods_session( + &self, + state: &common_utils::types::keymanager::KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + id: &common_utils::id_type::GlobalPaymentMethodSessionId, + ) -> CustomResult< + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + errors::StorageError, + >; +} + +#[cfg(feature = "v1")] +pub trait PaymentMethodsSessionInterface {} + +#[cfg(feature = "v1")] +impl PaymentMethodsSessionInterface for crate::services::Store {} + +#[cfg(feature = "v2")] +mod storage { + use error_stack::ResultExt; + use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; + use router_env::{instrument, tracing}; + use storage_impl::redis::kv_store::RedisConnInterface; + + use super::PaymentMethodsSessionInterface; + use crate::{ + core::errors::{self, CustomResult}, + services::Store, + }; + + #[async_trait::async_trait] + impl PaymentMethodsSessionInterface for Store { + #[instrument(skip_all)] + async fn insert_payment_methods_session( + &self, + _state: &common_utils::types::keymanager::KeyManagerState, + _key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + validity_in_seconds: i64, + ) -> CustomResult<(), errors::StorageError> { + let redis_key = payment_methods_session.id.get_redis_key(); + + let db_model = payment_methods_session + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)?; + + let redis_connection = self + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + redis_connection + .serialize_and_set_key_with_expiry(&redis_key.into(), db_model, validity_in_seconds) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("Failed to insert payment methods session to redis") + } + + #[instrument(skip_all)] + async fn get_payment_methods_session( + &self, + state: &common_utils::types::keymanager::KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + id: &common_utils::id_type::GlobalPaymentMethodSessionId, + ) -> CustomResult< + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + errors::StorageError, + > { + let redis_key = id.get_redis_key(); + + let redis_connection = self + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + let db_model = redis_connection + .get_and_deserialize_key::<diesel_models::payment_methods_session::PaymentMethodsSession>(&redis_key.into(), "PaymentMethodsSession") + .await + .change_context(errors::StorageError::KVError)?; + + let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant( + key_store.merchant_id.clone(), + ); + + db_model + .convert(state, &key_store.key, key_manager_identifier) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("Failed to decrypt payment methods session") + } + } +} + +#[cfg(feature = "v2")] +#[async_trait::async_trait] +impl PaymentMethodsSessionInterface for MockDb { + async fn insert_payment_methods_session( + &self, + state: &common_utils::types::keymanager::KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + validity_in_seconds: i64, + ) -> CustomResult<(), errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + #[cfg(feature = "v2")] + async fn get_payment_methods_session( + &self, + state: &common_utils::types::keymanager::KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + id: &common_utils::id_type::GlobalPaymentMethodSessionId, + ) -> CustomResult< + hyperswitch_domain_models::payment_methods::PaymentMethodsSession, + errors::StorageError, + > { + Err(errors::StorageError::MockDbError)? + } +} + +#[cfg(feature = "v1")] +#[async_trait::async_trait] +impl PaymentMethodsSessionInterface for MockDb {} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 9febfa5e469..9b43d7f2b16 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -90,8 +90,8 @@ pub mod headers { pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; + pub const X_CUSTOMER_ID: &str = "X-Customer-Id"; pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; - pub const X_RESOURCE_TYPE: &str = "X-Resource-Type"; } pub mod pii { @@ -151,6 +151,11 @@ pub fn mk_app( server_app = server_app.service(routes::PaymentMethods::server(state.clone())); } + #[cfg(all(feature = "v2", feature = "oltp"))] + { + server_app = server_app.service(routes::PaymentMethodsSession::server(state.clone())); + } + #[cfg(feature = "v1")] { server_app = server_app diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 22f5983e4c3..80906570d7c 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -63,6 +63,8 @@ pub mod relay; #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; +#[cfg(feature = "v2")] +pub use self::app::PaymentMethodsSession; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub use self::app::Recon; pub use self::app::{ diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index e4da0119fdd..c5e1f8a1082 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1016,13 +1016,6 @@ impl Customers { .route(web::delete().to(customers::customers_delete)), ) } - #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))] - { - route = route.service( - web::resource("/{customer_id}/saved-payment-methods") - .route(web::get().to(payment_methods::list_customer_payment_method_api)), - ); - } route } } @@ -1182,14 +1175,9 @@ impl PaymentMethods { .route(web::get().to(payment_methods::payment_method_retrieve_api)) .route(web::delete().to(payment_methods::payment_method_delete_api)), ) - .service( - web::resource("/list-enabled-payment-methods") - .route(web::get().to(payment_methods::list_payment_methods_enabled)), - ) - .service( - web::resource("/confirm-intent") - .route(web::post().to(payment_methods::confirm_payment_method_intent_api)), - ) + .service(web::resource("/list-enabled-payment-methods").route( + web::get().to(payment_methods::payment_method_session_list_payment_methods), + )) .service( web::resource("/update-saved-payment-method") .route(web::put().to(payment_methods::payment_method_update_api)), @@ -1266,6 +1254,40 @@ impl PaymentMethods { } } +#[cfg(all(feature = "v2", feature = "oltp"))] +pub struct PaymentMethodsSession; + +#[cfg(all(feature = "v2", feature = "oltp"))] +impl PaymentMethodsSession { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/v2/payment-methods-session").app_data(web::Data::new(state)); + route = route.service( + web::resource("") + .route(web::post().to(payment_methods::payment_methods_session_create)), + ); + + route = route.service( + web::scope("/{payment_method_session_id}") + .service( + web::resource("") + .route(web::get().to(payment_methods::payment_methods_session_retrieve)), + ) + .service(web::resource("/list-payment-methods").route( + web::get().to(payment_methods::payment_method_session_list_payment_methods), + )) + .service( + web::resource("/update-saved-payment-method").route( + web::put().to( + payment_methods::payment_method_session_update_saved_payment_method, + ), + ), + ), + ); + + route + } +} + #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub struct Recon; @@ -1483,10 +1505,10 @@ impl EphemeralKey { #[cfg(feature = "v2")] impl EphemeralKey { pub fn server(config: AppState) -> Scope { - web::scope("/v2/ephemeral-keys") + web::scope("/v2/client-secret") .app_data(web::Data::new(config)) - .service(web::resource("").route(web::post().to(ephemeral_key_create))) - .service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete))) + .service(web::resource("").route(web::post().to(client_secret_create))) + .service(web::resource("/{id}").route(web::delete().to(client_secret_delete))) } } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 09b6983d2a7..20f53c17aa0 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -85,19 +85,21 @@ pub async fn customers_retrieve( req: HttpRequest, path: web::Path<id_type::GlobalCustomerId>, ) -> HttpResponse { + use crate::services::authentication::api_or_client_auth; + let flow = Flow::CustomersRetrieve; let id = path.into_inner(); + let v2_client_auth = auth::V2ClientAuth( + common_utils::types::authentication::ResourceId::Customer(id.clone()), + ); let auth = if auth::is_jwt_auth(req.headers()) { - Box::new(auth::JWTAuth { + &auth::JWTAuth { permission: Permission::MerchantCustomerRead, - }) - } else { - match auth::is_ephemeral_auth(req.headers()) { - Ok(auth) => auth, - Err(err) => return api::log_and_return_error_response(err), } + } else { + api_or_client_auth(&auth::V2ApiKeyAuth, &v2_client_auth, req.headers()) }; Box::pin(api::server_wrap( @@ -108,7 +110,7 @@ pub async fn customers_retrieve( |state, auth: auth::AuthenticationData, id, _| { retrieve_customer(state, auth.merchant_account, auth.key_store, id) }, - &*auth, + auth, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index 0330482e81a..92b5d667daa 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -7,7 +7,7 @@ use crate::{ services::{api, authentication as auth}, }; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] +#[cfg(all(feature = "v1", not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] pub async fn ephemeral_key_create( state: web::Data<AppState>, @@ -34,12 +34,33 @@ pub async fn ephemeral_key_create( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))] +pub async fn ephemeral_key_delete( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::EphemeralKeyDelete; + let payload = path.into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req), + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + ) + .await +} + #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] -pub async fn ephemeral_key_create( +pub async fn client_secret_create( state: web::Data<AppState>, req: HttpRequest, - json_payload: web::Json<api_models::ephemeral_key::EphemeralKeyCreateRequest>, + json_payload: web::Json<api_models::ephemeral_key::ClientSecretCreateRequest>, ) -> HttpResponse { let flow = Flow::EphemeralKeyCreate; let payload = json_payload.into_inner(); @@ -49,9 +70,9 @@ pub async fn ephemeral_key_create( &req, payload, |state, auth: auth::AuthenticationData, payload, _| { - helpers::make_ephemeral_key( + helpers::make_client_secret( state, - payload.customer_id.to_owned(), + payload.resource_id.to_owned(), auth.merchant_account, auth.key_store, req.headers(), @@ -63,8 +84,9 @@ pub async fn ephemeral_key_create( .await } +#[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))] -pub async fn ephemeral_key_delete( +pub async fn client_secret_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, @@ -76,7 +98,7 @@ pub async fn ephemeral_key_delete( state, &req, payload, - |state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req), + |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req), &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index b09f92364bc..ce9dda97c9f 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -39,6 +39,7 @@ pub enum ApiIdentifier { ApplePayCertificatesMigration, Relay, Documentation, + PaymentMethodsSession, } impl From<Flow> for ApiIdentifier { @@ -309,6 +310,10 @@ impl From<Flow> for ApiIdentifier { Flow::RetrievePollStatus => Self::Poll, Flow::FeatureMatrix => Self::Documentation, + + Flow::PaymentMethodSessionCreate + | Flow::PaymentMethodSessionRetrieve + | Flow::PaymentMethodSessionUpdateSavedPaymentMethod => Self::PaymentMethodsSession, } } } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 5f9fe729eeb..86f1874ab09 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -11,12 +11,6 @@ use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::core::payment_methods::{ - create_payment_method, delete_payment_method, list_customer_payment_method_util, - payment_method_intent_confirm, payment_method_intent_create, retrieve_payment_method, - update_payment_method, -}; use crate::{ core::{ api_locking, @@ -86,7 +80,7 @@ pub async fn create_payment_method_api( &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { - Box::pin(create_payment_method( + Box::pin(payment_methods_routes::create_payment_method( &state, req, &auth.merchant_account, @@ -115,7 +109,7 @@ pub async fn create_payment_method_intent_api( &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { - Box::pin(payment_method_intent_create( + Box::pin(payment_methods_routes::payment_method_intent_create( &state, req, &auth.merchant_account, @@ -123,7 +117,7 @@ pub async fn create_payment_method_intent_api( )) .await }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -134,21 +128,13 @@ pub async fn create_payment_method_intent_api( #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, - pub payment_method_type: common_enums::PaymentMethod, - pub payment_method_subtype: common_enums::PaymentMethodType, - pub customer_id: Option<id_type::CustomerId>, - pub payment_method_data: payment_methods::PaymentMethodCreateData, + pub request: payment_methods::PaymentMethodIntentConfirm, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { - Self { - payment_method_type: item.payment_method_type, - payment_method_subtype: item.payment_method_subtype, - customer_id: item.customer_id, - payment_method_data: item.payment_method_data.clone(), - } + item.request } } @@ -157,128 +143,39 @@ impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), - payment_method_type: Some(self.payment_method_type), - payment_method_subtype: Some(self.payment_method_subtype), + payment_method_type: Some(self.request.payment_method_type), + payment_method_subtype: Some(self.request.payment_method_subtype), }) } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] -pub async fn confirm_payment_method_intent_api( - state: web::Data<AppState>, - req: HttpRequest, - json_payload: web::Json<payment_methods::PaymentMethodIntentConfirm>, - path: web::Path<id_type::GlobalPaymentMethodId>, -) -> HttpResponse { - let flow = Flow::PaymentMethodsCreate; - let pm_id = path.into_inner(); - let payload = json_payload.into_inner(); - - let auth = match auth::is_ephemeral_or_publishible_auth(req.headers()) { - Ok(auth) => auth, - Err(e) => return api::log_and_return_error_response(e), - }; - - let inner_payload = PaymentMethodIntentConfirmInternal { - id: pm_id.to_owned(), - payment_method_type: payload.payment_method_type, - payment_method_subtype: payload.payment_method_subtype, - customer_id: payload.customer_id.to_owned(), - payment_method_data: payload.payment_method_data.clone(), - }; - - Box::pin(api::server_wrap( - flow, - state, - &req, - inner_payload, - |state, auth: auth::AuthenticationData, req, _| { - let pm_id = pm_id.clone(); - async move { - Box::pin(payment_method_intent_confirm( - &state, - req.into(), - &auth.merchant_account, - &auth.key_store, - pm_id, - )) - .await - } - }, - &*auth, - api_locking::LockAction::NotApplicable, - )) - .await -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] -pub async fn list_payment_methods_enabled( - state: web::Data<AppState>, - req: HttpRequest, - path: web::Path<id_type::GlobalPaymentMethodId>, -) -> HttpResponse { - let flow = Flow::PaymentMethodsList; - let payment_method_id = path.into_inner(); - - let auth = match auth::is_ephemeral_or_publishible_auth(req.headers()) { - Ok(auth) => auth, - Err(e) => return api::log_and_return_error_response(e), - }; - - Box::pin(api::server_wrap( - flow, - state, - &req, - payment_method_id, - |state, auth: auth::AuthenticationData, payment_method_id, _| { - payment_methods_routes::list_payment_methods_enabled( - state, - auth.merchant_account, - auth.key_store, - auth.profile, - payment_method_id, - ) - }, - &*auth, - api_locking::LockAction::NotApplicable, - )) - .await -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<String>, + path: web::Path<id_type::GlobalPaymentMethodId>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); - let auth = match auth::is_ephemeral_or_publishible_auth(req.headers()) { - Ok(auth) => auth, - Err(e) => return api::log_and_return_error_response(e), - }; - Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { - update_payment_method( + payment_methods_routes::update_payment_method( state, auth.merchant_account, + auth.key_store, req, &payment_method_id, - auth.key_store, ) }, - &*auth, + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -303,7 +200,12 @@ pub async fn payment_method_retrieve_api( &req, payload, |state, auth: auth::AuthenticationData, pm, _| { - retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account) + payment_methods_routes::retrieve_payment_method( + state, + pm, + auth.key_store, + auth.merchant_account, + ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, @@ -330,7 +232,12 @@ pub async fn payment_method_delete_api( &req, payload, |state, auth: auth::AuthenticationData, pm, _| { - delete_payment_method(state, pm, auth.key_store, auth.merchant_account) + payment_methods_routes::delete_payment_method( + state, + pm, + auth.key_store, + auth.merchant_account, + ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, @@ -580,49 +487,6 @@ pub async fn list_customer_payment_method_api( .await } -#[cfg(all( - feature = "v2", - feature = "payment_methods_v2", - feature = "customer_v2" -))] -#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] -pub async fn list_customer_payment_method_api( - state: web::Data<AppState>, - customer_id: web::Path<id_type::GlobalCustomerId>, - req: HttpRequest, - query_payload: web::Query<api_models::payment_methods::PaymentMethodListRequest>, -) -> HttpResponse { - let flow = Flow::CustomerPaymentMethodsList; - let payload = query_payload.into_inner(); - let customer_id = customer_id.into_inner(); - - let ephemeral_or_api_auth = match auth::is_ephemeral_auth(req.headers()) { - Ok(auth) => auth, - Err(err) => return api::log_and_return_error_response(err), - }; - - Box::pin(api::server_wrap( - flow, - state, - &req, - payload, - |state, auth: auth::AuthenticationData, req, _| { - list_customer_payment_method_util( - state, - auth.merchant_account, - auth.profile, - auth.key_store, - Some(req), - Some(customer_id.clone()), - false, - ) - }, - &*ephemeral_or_api_auth, - api_locking::LockAction::NotApplicable, - )) - .await -} - #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2"), @@ -1022,3 +886,167 @@ impl ParentPaymentMethodToken { } } } + +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))] +pub async fn payment_methods_session_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionRequest>, +) -> HttpResponse { + let flow = Flow::PaymentMethodSessionCreate; + let payload = json_payload.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, request, _| async move { + payment_methods_routes::payment_methods_session_create( + state, + auth.merchant_account, + auth.key_store, + request, + ) + .await + }, + &auth::V2ApiKeyAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionRetrieve))] +pub async fn payment_methods_session_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<id_type::GlobalPaymentMethodSessionId>, +) -> HttpResponse { + let flow = Flow::PaymentMethodSessionRetrieve; + let payment_method_session_id = path.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payment_method_session_id.clone(), + |state, auth: auth::AuthenticationData, payment_method_session_id, _| async move { + payment_methods_routes::payment_methods_session_retrieve( + state, + auth.merchant_account, + auth.key_store, + payment_method_session_id, + ) + .await + }, + auth::api_or_client_auth( + &auth::V2ApiKeyAuth, + &auth::V2ClientAuth( + common_utils::types::authentication::ResourceId::PaymentMethodSession( + payment_method_session_id, + ), + ), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] +pub async fn payment_method_session_list_payment_methods( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<id_type::GlobalPaymentMethodSessionId>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsList; + let payment_method_session_id = path.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payment_method_session_id.clone(), + |state, auth: auth::AuthenticationData, payment_method_session_id, _| { + payment_methods_routes::list_payment_methods_for_session( + state, + auth.merchant_account, + auth.key_store, + auth.profile, + payment_method_session_id, + ) + }, + &auth::V2ClientAuth( + common_utils::types::authentication::ResourceId::PaymentMethodSession( + payment_method_session_id, + ), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Serialize)] +struct PaymentMethodsSessionGenericRequest<T: serde::Serialize> { + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, + #[serde(flatten)] + request: T, +} + +#[cfg(feature = "v2")] +impl<T: serde::Serialize> common_utils::events::ApiEventMetric + for PaymentMethodsSessionGenericRequest<T> +{ + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::PaymentMethodSession { + payment_method_session_id: self.payment_method_session_id.clone(), + }) + } +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] +pub async fn payment_method_session_update_saved_payment_method( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<id_type::GlobalPaymentMethodSessionId>, + json_payload: web::Json< + api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, + >, +) -> HttpResponse { + let flow = Flow::PaymentMethodSessionUpdateSavedPaymentMethod; + let payload = json_payload.into_inner(); + let payment_method_session_id = path.into_inner(); + + let request = PaymentMethodsSessionGenericRequest { + payment_method_session_id: payment_method_session_id.clone(), + request: payload, + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + request, + |state, auth: auth::AuthenticationData, request, _| { + payment_methods_routes::payment_methods_session_update_payment_method( + state, + auth.merchant_account, + auth.key_store, + request.payment_method_session_id, + request.request, + ) + }, + &auth::V2ClientAuth( + common_utils::types::authentication::ResourceId::PaymentMethodSession( + payment_method_session_id, + ), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 99800b55512..edf127ac30f 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -20,6 +20,8 @@ use common_utils::{date_time, id_type}; use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; +#[cfg(feature = "v2")] +use masking::ExposeInterface; use masking::PeekInterface; use router_env::logger; use serde::Serialize; @@ -1286,6 +1288,17 @@ impl<'a> HeaderMapStruct<'a> { }) } + pub fn get_auth_string_from_header(&self) -> RouterResult<&str> { + self.headers + .get(headers::AUTHORIZATION) + .get_required_value(headers::AUTHORIZATION)? + .to_str() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: headers::AUTHORIZATION, + }) + .attach_printable("Failed to convert authorization header to string") + } + pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>> where T: TryFrom< @@ -1510,44 +1523,6 @@ where } } -#[cfg(feature = "v2")] -#[async_trait] -impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth -where - A: SessionStateInfo + Sync, -{ - async fn authenticate_and_fetch( - &self, - request_headers: &HeaderMap, - state: &A, - ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let api_key = - get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; - let ephemeral_key = state - .store() - .get_ephemeral_key(api_key) - .await - .change_context(errors::ApiErrorResponse::Unauthorized)?; - - let resource_type = HeaderMapStruct::new(request_headers) - .get_mandatory_header_value_by_key(headers::X_RESOURCE_TYPE) - .and_then(|val| { - ephemeral_key::ResourceType::from_str(val).change_context( - errors::ApiErrorResponse::InvalidRequestData { - message: format!("`{}` header is invalid", headers::X_RESOURCE_TYPE), - }, - ) - })?; - - fp_utils::when(resource_type != ephemeral_key.resource_type, || { - Err(errors::ApiErrorResponse::Unauthorized) - })?; - - MerchantIdAuth(ephemeral_key.merchant_id) - .authenticate_and_fetch(request_headers, state) - .await - } -} #[derive(Debug)] pub struct MerchantIdAuth(pub id_type::MerchantId); @@ -1778,6 +1753,249 @@ where } } +/// Take api-key from `Authorization` header +#[cfg(feature = "v2")] +#[derive(Debug)] +pub struct V2ApiKeyAuth; + +#[cfg(feature = "v2")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ApiKeyAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let header_map_struct = HeaderMapStruct::new(request_headers); + let auth_string = header_map_struct.get_auth_string_from_header()?; + + let api_key = auth_string + .split(',') + .find_map(|part| part.trim().strip_prefix("api-key=")) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Unable to parse api_key") + })?; + if api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("API key is empty"); + } + + let profile_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; + + let api_key = api_keys::PlaintextApiKey::from(api_key); + let hash_key = { + let config = state.conf(); + config.api_keys.get_inner().get_hash_key()? + }; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + let key_manager_state = &(&state.session_state()).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + + let profile = state + .store() + .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account, + key_store, + profile, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + +#[cfg(feature = "v2")] +#[derive(Debug)] +pub struct V2ClientAuth(pub common_utils::types::authentication::ResourceId); + +#[cfg(feature = "v2")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ClientAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let header_map_struct = HeaderMapStruct::new(request_headers); + let auth_string = header_map_struct.get_auth_string_from_header()?; + + let publishable_key = auth_string + .split(',') + .find_map(|part| part.trim().strip_prefix("publishable-key=")) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Unable to parse publishable_key") + })?; + + let client_secret = auth_string + .split(',') + .find_map(|part| part.trim().strip_prefix("client-secret=")) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Unable to parse client_secret") + })?; + + let key_manager_state: &common_utils::types::keymanager::KeyManagerState = + &(&state.session_state()).into(); + + let db_client_secret: diesel_models::ClientSecretType = state + .store() + .get_client_secret(client_secret) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Invalid ephemeral_key")?; + + let profile_id = + get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? + .get_required_value(headers::X_PROFILE_ID)?; + + match db_client_secret.resource_id { + common_utils::types::authentication::ResourceId::Payment(global_payment_id) => { + return Err(errors::ApiErrorResponse::Unauthorized.into()) + } + common_utils::types::authentication::ResourceId::Customer(global_customer_id) => { + if global_customer_id.get_string_repr() != self.0.to_str() { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } + common_utils::types::authentication::ResourceId::PaymentMethodSession( + global_payment_method_session_id, + ) => { + if global_payment_method_session_id.get_string_repr() != self.0.to_str() { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } + }; + + let (merchant_account, key_store) = state + .store() + .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + let merchant_id = merchant_account.get_id().clone(); + + if db_client_secret.merchant_id != merchant_id { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + let profile = state + .store() + .find_business_profile_by_merchant_id_profile_id( + key_manager_state, + &key_store, + &merchant_id, + &profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + Ok(( + AuthenticationData { + merchant_account, + key_store, + profile, + platform_merchant_account: None, + }, + AuthenticationType::PublishableKey { merchant_id }, + )) + } +} + +#[cfg(feature = "v2")] +pub fn api_or_client_auth<'a, T, A>( + api_auth: &'a dyn AuthenticateAndFetch<T, A>, + client_auth: &'a dyn AuthenticateAndFetch<T, A>, + headers: &HeaderMap, +) -> &'a dyn AuthenticateAndFetch<T, A> +where +{ + if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() { + if val.trim().starts_with("api-key=") { + api_auth + } else { + client_auth + } + } else { + api_auth + } +} + #[derive(Debug)] pub struct PublishableKeyAuth; @@ -3282,20 +3500,7 @@ where } } -pub fn is_ephemeral_or_publishible_auth<A: SessionStateInfo + Sync + Send>( - headers: &HeaderMap, -) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { - let api_key = get_api_key(headers)?; - - if api_key.starts_with("epk") { - Ok(Box::new(EphemeralKeyAuth)) - } else if api_key.starts_with("pk_") { - Ok(Box::new(HeaderAuth(PublishableKeyAuth))) - } else { - Ok(Box::new(HeaderAuth(ApiKeyAuth))) - } -} - +#[cfg(feature = "v1")] pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { @@ -3309,10 +3514,13 @@ pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( } pub fn is_jwt_auth(headers: &HeaderMap) -> bool { - headers.get(headers::AUTHORIZATION).is_some() - || get_cookie_from_header(headers) + let header_map_struct = HeaderMapStruct::new(headers); + match header_map_struct.get_auth_string_from_header() { + Ok(auth_str) => auth_str.starts_with("Bearer"), + Err(_) => get_cookie_from_header(headers) .and_then(cookies::get_jwt_from_cookies) - .is_ok() + .is_ok(), + } } pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T> diff --git a/crates/router/src/types/storage/ephemeral_key.rs b/crates/router/src/types/storage/ephemeral_key.rs index c4b8e2ba701..46bf185194d 100644 --- a/crates/router/src/types/storage/ephemeral_key.rs +++ b/crates/router/src/types/storage/ephemeral_key.rs @@ -1,18 +1,33 @@ -pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew}; #[cfg(feature = "v2")] -pub use diesel_models::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew, ResourceType}; +pub use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; +pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew}; #[cfg(feature = "v2")] -use crate::types::transformers::ForeignFrom; +use crate::db::errors; +#[cfg(feature = "v2")] +use crate::types::transformers::ForeignTryFrom; #[cfg(feature = "v2")] -impl ForeignFrom<EphemeralKeyType> for api_models::ephemeral_key::EphemeralKeyResponse { - fn foreign_from(from: EphemeralKeyType) -> Self { - Self { - customer_id: from.customer_id, - created_at: from.created_at, - expires: from.expires, - secret: from.secret, - id: from.id, +impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecretResponse { + type Error = errors::ApiErrorResponse; + fn foreign_try_from(from: ClientSecretType) -> Result<Self, errors::ApiErrorResponse> { + match from.resource_id { + common_utils::types::authentication::ResourceId::Payment(global_payment_id) => { + Err(errors::ApiErrorResponse::InternalServerError) + } + common_utils::types::authentication::ResourceId::PaymentMethodSession( + global_payment_id, + ) => Err(errors::ApiErrorResponse::InternalServerError), + common_utils::types::authentication::ResourceId::Customer(global_customer_id) => { + Ok(Self { + resource_id: api_models::ephemeral_key::ResourceId::Customer( + global_customer_id.clone(), + ), + created_at: from.created_at, + expires: from.expires, + secret: from.secret, + id: from.id, + }) + } } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index acd6e59431c..b88effea34f 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -543,6 +543,12 @@ pub enum Flow { RelayRetrieve, /// Incoming Relay Webhook Receive IncomingRelayWebhookReceive, + /// Payment Method Session Create + PaymentMethodSessionCreate, + /// Payment Method Session Retrieve + PaymentMethodSessionRetrieve, + /// Update a saved payment method using the payment methods session + PaymentMethodSessionUpdateSavedPaymentMethod, } /// Trait for providing generic behaviour to flow metric
feat
add payment methods session endpoints (#7107)
9798db4558d926a218a0ca6f7f7c4e24a187b3da
2024-03-27 13:57:14
Prasunna Soppa
fix(trustpay): [Trustpay] Add error code mapping '800.100.100' (#4224)
false
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 9d5d2e3d749..d898bd24896 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -491,6 +491,7 @@ fn is_payment_failed(payment_status: &str) -> (bool, &'static str) { ), "700.500.001" => (true, "Referenced session contains too many transactions"), "700.500.003" => (true, "Test accounts not allowed in production"), + "800.100.100" => (true, "Transaction declined for unknown reason"), "800.100.151" => (true, "Transaction declined (invalid card)"), "800.100.152" => (true, "Transaction declined by authorization system"), "800.100.153" => (true, "Transaction declined (invalid CVV)"),
fix
[Trustpay] Add error code mapping '800.100.100' (#4224)
4851da1595074dbb2760e76f83403e8ac9f7895f
2024-04-22 18:45:13
Hrithikesh
chore: add wasm toml configs for netcetera authnetication connector (#4426)
false
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index d89516c0cc1..805c4a86cbc 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -87,6 +87,8 @@ pub struct ConfigMetadata { pub merchant_name: Option<String>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, + pub three_ds_requestor_name: Option<String>, + pub three_ds_requestor_id: Option<String>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 849da0d9236..b1c66ce1805 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2599,6 +2599,18 @@ mcc="MCC" merchant_country_code="3 digit numeric country code" merchant_name="Name of the merchant" +[netcetera] +[netcetera.connector_auth.CertificateAuth] +certificate="Base64 encoded PEM formatted certificate chain" +private_key="Base64 encoded PEM formatted private key" +[netcetera.metadata] +mcc="MCC" +merchant_country_code="3 digit numeric country code" +merchant_name="Name of the merchant" +endpoint_prefix="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" +three_ds_requestor_name="ThreeDS requestor name" +three_ds_requestor_id="ThreeDS request id" + [billwerk] [[billwerk.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 912949a3152..ee21ac99b8d 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -2601,6 +2601,18 @@ mcc="MCC" merchant_country_code="3 digit numeric country code" merchant_name="Name of the merchant" +[netcetera] +[netcetera.connector_auth.CertificateAuth] +certificate="Base64 encoded PEM formatted certificate chain" +private_key="Base64 encoded PEM formatted private key" +[netcetera.metadata] +mcc="MCC" +merchant_country_code="3 digit numeric country code" +merchant_name="Name of the merchant" +endpoint_prefix="string that will replace '{prefix}' in this base url 'https://{prefix}.3ds-server.prev.netcetera-cloud-payment.ch'" +three_ds_requestor_name="ThreeDS requestor name" +three_ds_requestor_id="ThreeDS request id" + [billwerk] [[billwerk.credit]] payment_method_type = "Mastercard"
chore
add wasm toml configs for netcetera authnetication connector (#4426)
1afc54837d5988eaf41f434474c30ec511681bbe
2023-07-21 18:45:54
Anup Jadhav
docs(postman): added a note about how postman now requires you to fork a collection in order to send a request (#1769)
false
diff --git a/docs/try_local_system.md b/docs/try_local_system.md index 9d58870bf1d..59df43f2481 100644 --- a/docs/try_local_system.md +++ b/docs/try_local_system.md @@ -474,7 +474,9 @@ Once you're done with configuring the application, proceed with than the provided default, update the `data` field present in the `routing_algorithm` field to your liking. - Click on the "Send" button to create a merchant account. + Click on the "Send" button to create a merchant account + (You may need to "create a fork" to fork this collection to your own + workspace to send a request). You should obtain a response containing most of the data included in the request, along with some additional fields. Store the merchant ID and publishable key returned in the response.
docs
added a note about how postman now requires you to fork a collection in order to send a request (#1769)
a2b17cbc96bf92a016047a3522e6ff3c1b1e6e2a
2024-06-10 18:17:53
Apoorv Dixit
ci(postman): add users collection (#4897)
false
diff --git a/Cargo.lock b/Cargo.lock index 228414c0194..77f9b33ddc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7021,6 +7021,7 @@ dependencies = [ name = "test_utils" version = "0.1.0" dependencies = [ + "anyhow", "async-trait", "base64 0.22.0", "clap", diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index 3b0dfe2b91d..6d8663c0300 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -14,6 +14,7 @@ payouts = [] [dependencies] async-trait = "0.1.79" +anyhow = "1.0.81" base64 = "0.22.0" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } rand = "0.8.5" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 3ba321c174e..4b41506fe2d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -76,6 +76,7 @@ pub struct ConnectorAuthentication { pub zen: Option<HeaderKey>, pub zsl: Option<BodyKey>, pub automation_configs: Option<AutomationConfigs>, + pub users: Option<UsersConfigs>, } impl Default for ConnectorAuthentication { @@ -339,3 +340,12 @@ pub enum ConnectorAuthType { #[default] NoKey, } + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct UsersConfigs { + pub user_email: String, + pub user_password: String, + pub wrong_password: String, + pub user_base_email_for_signup: String, + pub user_domain_for_signup: String, +} diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index ba0d2eb358b..5b56b9a0d1c 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -1,9 +1,10 @@ use std::process::{exit, Command}; +use anyhow::Result; use test_utils::newman_runner; -fn main() { - let mut runner = newman_runner::generate_newman_command(); +fn main() -> Result<()> { + let mut runner = newman_runner::generate_runner()?; // Execute the newman command let output = runner.newman_command.spawn(); diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index c90292683ff..29c15789cce 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -6,14 +6,23 @@ use std::{ process::{exit, Command}, }; -use clap::{arg, command, Parser}; +use anyhow::{Context, Result}; +use clap::{arg, command, Parser, ValueEnum}; use masking::PeekInterface; use regex::Regex; -use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap}; +use crate::connector_auth::{ + ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap, +}; + +#[derive(ValueEnum, Clone, Copy)] +pub enum Module { + Connector, + Users, +} #[derive(Parser)] #[command(version, about = "Postman collection runner using newman!", long_about = None)] -struct Args { +pub struct Args { /// Admin API Key of the environment #[arg(short, long)] admin_api_key: String, @@ -22,7 +31,10 @@ struct Args { base_url: String, /// Name of the connector #[arg(short, long)] - connector_name: String, + connector_name: Option<String>, + /// Name of the module + #[arg(short, long)] + module_name: Option<Module>, /// Custom headers #[arg(short = 'H', long = "header")] custom_headers: Option<Vec<String>>, @@ -38,6 +50,13 @@ struct Args { verbose: bool, } +impl Args { + /// Getter for the `module_name` field + pub fn get_module_name(&self) -> Option<Module> { + self.module_name + } +} + pub struct ReturnArgs { pub newman_command: Command, pub modified_file_paths: Vec<Option<String>>, @@ -82,10 +101,93 @@ where Ok(()) } -pub fn generate_newman_command() -> ReturnArgs { +// This function gives runner for connector or a module +pub fn generate_runner() -> Result<ReturnArgs> { + let args = Args::parse(); + + match args.get_module_name() { + Some(Module::Users) => generate_newman_command_for_users(), + Some(Module::Connector) => generate_newman_command_for_connector(), + // Running connector tests when no module is passed to keep the previous test behavior same + None => generate_newman_command_for_connector(), + } +} + +pub fn generate_newman_command_for_users() -> Result<ReturnArgs> { + let args = Args::parse(); + let base_url = args.base_url; + let admin_api_key = args.admin_api_key; + + let path = env::var("CONNECTOR_AUTH_FILE_PATH") + .with_context(|| "connector authentication file path not set")?; + + let authentication: ConnectorAuthentication = toml::from_str( + &fs::read_to_string(path) + .with_context(|| "connector authentication config file not found")?, + ) + .with_context(|| "connector authentication file path not set")?; + + let users_configs = authentication + .users + .with_context(|| "user configs not found in authentication file")?; + let collection_path = get_collection_path("users"); + + let mut newman_command = Command::new("newman"); + newman_command.args(["run", &collection_path]); + newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]); + newman_command.args(["--env-var", &format!("baseUrl={base_url}")]); + newman_command.args([ + "--env-var", + &format!("user_email={}", users_configs.user_email), + ]); + newman_command.args([ + "--env-var", + &format!( + "user_base_email_for_signup={}", + users_configs.user_base_email_for_signup + ), + ]); + newman_command.args([ + "--env-var", + &format!( + "user_domain_for_signup={}", + users_configs.user_domain_for_signup + ), + ]); + newman_command.args([ + "--env-var", + &format!("user_password={}", users_configs.user_password), + ]); + newman_command.args([ + "--env-var", + &format!("wrong_password={}", users_configs.wrong_password), + ]); + + newman_command.args([ + "--delay-request", + format!("{}", &args.delay_request).as_str(), + ]); + + newman_command.arg("--color").arg("on"); + + if args.verbose { + newman_command.arg("--verbose"); + } + + Ok(ReturnArgs { + newman_command, + modified_file_paths: vec![], + collection_path, + }) +} + +pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> { let args = Args::parse(); - let connector_name = args.connector_name; + let connector_name = args + .connector_name + .with_context(|| "invalid parameters: connector/module name not found in arguments")?; + let base_url = args.base_url; let admin_api_key = args.admin_api_key; @@ -216,11 +318,11 @@ pub fn generate_newman_command() -> ReturnArgs { newman_command.arg("--verbose"); } - ReturnArgs { + Ok(ReturnArgs { newman_command, modified_file_paths: vec![modified_collection_file_paths, custom_header_exist], collection_path, - } + }) } pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> { diff --git a/postman/collection-dir/users/.event.meta.json b/postman/collection-dir/users/.event.meta.json new file mode 100644 index 00000000000..2df9d47d936 --- /dev/null +++ b/postman/collection-dir/users/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.prerequest.js", + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/.info.json b/postman/collection-dir/users/.info.json new file mode 100644 index 00000000000..68f1e83b8ef --- /dev/null +++ b/postman/collection-dir/users/.info.json @@ -0,0 +1,9 @@ +{ + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + } +} diff --git a/postman/collection-dir/users/.meta.json b/postman/collection-dir/users/.meta.json new file mode 100644 index 00000000000..91b6a65c5bc --- /dev/null +++ b/postman/collection-dir/users/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Health check", + "Flow Testcases" + ] +} diff --git a/postman/collection-dir/users/.variable.json b/postman/collection-dir/users/.variable.json new file mode 100644 index 00000000000..fba5b17b2fd --- /dev/null +++ b/postman/collection-dir/users/.variable.json @@ -0,0 +1,126 @@ +{ + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "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" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/.meta.json b/postman/collection-dir/users/Flow Testcases/.meta.json new file mode 100644 index 00000000000..3e649dae4eb --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Sign Up", + "Sign In" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json new file mode 100644 index 00000000000..84ed2cb9494 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json @@ -0,0 +1,8 @@ +{ + "childrenOrder": [ + "Signin", + "Signin Wrong", + "Signin Token Only", + "Signin Token Only Wrong" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js new file mode 100644 index 00000000000..16fca64a141 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js @@ -0,0 +1,16 @@ +// Validate status 4xx +pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () { + pm.response.to.have.status(401); +}); + +// Validate if response header has matching content-type +pm.test("[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json new file mode 100644 index 00000000000..7fee4c465c8 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json @@ -0,0 +1,37 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{wrong_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js new file mode 100644 index 00000000000..a8b3658e5ff --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::user/v2/signin?token_only=true - Response contains token", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("token"); + pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty; +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json new file mode 100644 index 00000000000..62028501a50 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json @@ -0,0 +1,37 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{user_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js new file mode 100644 index 00000000000..e0149290da6 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js @@ -0,0 +1,16 @@ +// Validate status code is 4xx Bad Request +pm.test("[POST]::/user/v2/signin - Status code is 401", function () { + pm.response.to.have.status(401); +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json new file mode 100644 index 00000000000..775b0972d57 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json @@ -0,0 +1,31 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{wrong_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js new file mode 100644 index 00000000000..174cbd8e5e2 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::/user/v2/signin - Response contains token", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("token"); + pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty; +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json new file mode 100644 index 00000000000..1d23f6e9652 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json @@ -0,0 +1,31 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{user_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json new file mode 100644 index 00000000000..07d803fb1ca --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "Connect Account" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js new file mode 100644 index 00000000000..7f16342a8ad --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js @@ -0,0 +1,8 @@ + +var baseEmail = pm.environment.get('user_base_email_for_signup'); +var emailDomain = pm.environment.get("user_domain_for_signup"); + +// Generate a unique email address +var uniqueEmail = baseEmail + new Date().getTime() + emailDomain; +// Set the unique email address as an environment variable +pm.environment.set('unique_email', uniqueEmail); diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js new file mode 100644 index 00000000000..6dbed06b0f6 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::/user/connect_account - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/connect_account - 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]::/user/connect_account - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::/user/connect_account - Response contains is_email_sent", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("is_email_sent"); + pm.expect(jsonData.is_email_sent).to.be.true; +}); diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json new file mode 100644 index 00000000000..d5f2433ad7a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json @@ -0,0 +1,29 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{unique_email}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Health check/.meta.json b/postman/collection-dir/users/Health check/.meta.json new file mode 100644 index 00000000000..66ee7e50cab --- /dev/null +++ b/postman/collection-dir/users/Health check/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "New Request" + ] +} diff --git a/postman/collection-dir/users/Health check/New Request/.event.meta.json b/postman/collection-dir/users/Health check/New Request/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Health check/New Request/event.test.js b/postman/collection-dir/users/Health check/New Request/event.test.js new file mode 100644 index 00000000000..5e5505dfa3b --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/event.test.js @@ -0,0 +1,4 @@ +// Validate status 2xx +pm.test("[POST]::/health - Status code is 2xx", function () { + pm.response.to.be.success; +}); diff --git a/postman/collection-dir/users/Health check/New Request/request.json b/postman/collection-dir/users/Health check/New Request/request.json new file mode 100644 index 00000000000..4e1e0a0d9e6 --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/request.json @@ -0,0 +1,13 @@ +{ + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } +} diff --git a/postman/collection-dir/users/Health check/New Request/response.json b/postman/collection-dir/users/Health check/New Request/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/event.prerequest.js b/postman/collection-dir/users/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/users/event.test.js b/postman/collection-dir/users/event.test.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json new file mode 100644 index 00000000000..943d37d22d3 --- /dev/null +++ b/postman/collection-json/users.postman_collection.json @@ -0,0 +1,556 @@ +{ + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "item": [ + { + "name": "Health check", + "item": [ + { + "name": "New Request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "Sign Up", + "item": [ + { + "name": "Connect Account", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/connect_account - 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]::/user/connect_account - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"is_email_sent\");", + " pm.expect(jsonData.is_email_sent).to.be.true;", + "});", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "", + "var baseEmail = pm.environment.get('user_base_email_for_signup');", + "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", + "", + "// Generate a unique email address", + "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", + "// Set the unique email address as an environment variable", + "pm.environment.set('unique_email', uniqueEmail);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{unique_email}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Sign In", + "item": [ + { + "name": "Signin", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status code is 4xx Bad Request", + "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + } + ] + } + ] + } + ], + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + }, + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "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" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +}
ci
add users collection (#4897)
2f6c00a1fd853876333608a7d1fa6b488c3001d3
2023-10-11 14:38:04
Rutam Prita Mishra
feat(connector): [NexiNets] Update connector_response_reference_id as reference to merchant (#2537)
false
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 5949e48ae18..7b2a41cfb0b 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -364,7 +364,7 @@ impl<F, T> mandate_reference, connector_metadata: Some(connector_metadata), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id), }), ..item.data }) @@ -425,7 +425,7 @@ impl<F, T> let transaction_id = Some(item.response.transaction_id.clone()); let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { transaction_id, - order_id: Some(item.response.order.order_id), + order_id: Some(item.response.order.order_id.clone()), psync_flow: item.response.transaction_type.clone(), }) .into_report() @@ -447,7 +447,7 @@ impl<F, T> mandate_reference: None, connector_metadata: Some(connector_metadata), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order.order_id), }), ..item.data })
feat
[NexiNets] Update connector_response_reference_id as reference to merchant (#2537)
eddcc3455b91569d60ecc955c0ba62d71dc8fefd
2023-06-28 18:56:52
Swangi Kumari
test(connector): [Adyen] Add test for bank debits, bank redirects, and wallets (#1260)
false
diff --git a/crates/router/tests/connectors/adyen_uk_ui.rs b/crates/router/tests/connectors/adyen_uk_ui.rs index 2ffbd99cbc3..fef4026e84c 100644 --- a/crates/router/tests/connectors/adyen_uk_ui.rs +++ b/crates/router/tests/connectors/adyen_uk_ui.rs @@ -13,27 +13,25 @@ impl SeleniumTest for AdyenSeleniumTest { async fn should_make_adyen_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; - let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=70.00&country=US&currency=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD"), vec![ - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), ]).await?; Ok(()) } async fn should_make_adyen_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; - let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"), vec![ - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), ]).await?; Ok(()) } @@ -42,16 +40,15 @@ async fn should_make_adyen_gpay_zero_dollar_mandate_payment( c: WebDriver, ) -> Result<(), WebDriverError> { let conn = AdyenSeleniumTest {}; - let pub_key = conn.get_configs().adyen_uk.unwrap().key1; conn.make_gpay_payment(c, - &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid={pub_key}&amount=0.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), + &format!("{CHEKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"), vec![ - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), ]).await?; Ok(()) } @@ -74,12 +71,12 @@ async fn should_make_adyen_klarna_mandate_payment(c: WebDriver) -> Result<(), We ] ), Event::Trigger(Trigger::SwitchTab(Position::Prev)), - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ - Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Id("pm-mandate-btn"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), - Event::Assert(Assert::IsPresent("processing")), + Event::Assert(Assert::IsPresent("succeeded")), ]).await?; Ok(()) } diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index cbf80299e74..5936350dc82 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -230,16 +230,18 @@ pub trait SeleniumTest { } Trigger::Click(by) => { let ele = driver.query(by).first().await?; + ele.wait_until().enabled().await?; ele.wait_until().displayed().await?; ele.wait_until().clickable().await?; - ele.wait_until().enabled().await?; + ele.scroll_into_view().await?; ele.click().await?; } Trigger::ClickNth(by, n) => { let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap(); + ele.wait_until().enabled().await?; ele.wait_until().displayed().await?; ele.wait_until().clickable().await?; - ele.wait_until().enabled().await?; + ele.scroll_into_view().await?; ele.click().await?; } Trigger::Find(by) => { diff --git a/crates/router/tests/connectors/stripe_ui.rs b/crates/router/tests/connectors/stripe_ui.rs index 9fc19d94317..9e7d0cd63da 100644 --- a/crates/router/tests/connectors/stripe_ui.rs +++ b/crates/router/tests/connectors/stripe_ui.rs @@ -34,6 +34,7 @@ async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverEr Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), Event::Assert(Assert::IsPresent("succeeded")), @@ -53,6 +54,7 @@ async fn should_fail_recurring_payment_due_to_authentication( Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), Event::Assert(Assert::IsPresent("authentication_required: Your card was declined. This transaction requires authentication.")), @@ -72,6 +74,7 @@ async fn should_make_3ds_mandate_with_zero_dollar_payment( Event::Assert(Assert::IsPresent("Mandate ID")), Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_ Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), + Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))), Event::Trigger(Trigger::Click(By::Id("pay-with-mandate-btn"))), // Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method Event::Assert(Assert::IsPresent("succeeded")),
test
[Adyen] Add test for bank debits, bank redirects, and wallets (#1260)
da6a026ef772dcdde6bc99a38e0a17496adf4760
2023-01-21 23:34:44
SamraatBansal
feat(connector): add auth_token_refresh for payu and some quick bug fixes (#426)
false
diff --git a/config/Development.toml b/config/Development.toml index 33fe4f74c7b..29ed380b7cc 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -43,7 +43,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay", "fiserv", "worldline"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay", "fiserv", "payu", "worldline"] [refund] max_attempts = 10 @@ -92,7 +92,7 @@ base_url = "https://cert.api.fiservapps.com/" base_url = "http://localhost:9090/" [connectors.payu] -base_url = "https://secure.snd.payu.com/api/" +base_url = "https://secure.snd.payu.com/" [connectors.globalpay] base_url = "https://apis.sandbox.globalpay.com/ucp/" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 1bd75a634fc..dc8666b10b8 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -529,7 +529,7 @@ pub enum Connector { impl Connector { pub fn supports_access_token(&self) -> bool { - matches!(self, Self::Globalpay) + matches!(self, Self::Globalpay | Self::Payu) } } diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 930ae3ab51f..bf553f3639d 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -19,7 +19,7 @@ use crate::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, - utils::{self, BytesExt}, + utils::{self, BytesExt, OptionExt}, }; #[derive(Debug, Clone)] @@ -633,10 +633,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let refund_id = req + .response + .clone() + .ok() + .get_required_value("response") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + .connector_refund_id; Ok(format!( "{}tss/v2/transactions/{}", self.base_url(connectors), - req.request.connector_transaction_id + refund_id )) } fn build_request( diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index a16fdea007a..b998db5d70f 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -197,7 +197,7 @@ pub struct FiservPaymentsResponse { #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct GatewayResponse { - gateway_transaction_id: String, + gateway_transaction_id: Option<String>, transaction_state: FiservPaymentStatus, transaction_processing_details: TransactionProcessingDetails, } diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 6d2b2be63a5..25b5a0fb068 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -26,7 +26,7 @@ use crate::{ api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, }, - utils::{self, BytesExt}, + utils::{self, BytesExt, OptionExt}, }; #[derive(Debug, Clone)] @@ -633,10 +633,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let refund_id = req + .response + .clone() + .ok() + .get_required_value("response") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + .connector_refund_id; Ok(format!( "{}transactions/{}", self.base_url(connectors), - req.request.connector_transaction_id + refund_id )) } diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index f7ffc31b713..23546799187 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -11,7 +11,8 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, services, + headers, logger, + services::{self, ConnectorIntegration}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, @@ -25,20 +26,29 @@ pub struct Payu; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payu where - Self: services::ConnectorIntegration<Flow, Request, Response>, + Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let mut header = vec![( + let mut headers = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self).to_string(), + self.get_content_type().to_string(), )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + let access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + + let auth_header = ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token), + ); + + headers.push(auth_header); + Ok(headers) } } @@ -64,10 +74,12 @@ impl ConnectorCommon for Payu { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) } + fn build_error_response( &self, res: types::Response, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + logger::debug!(payu_error_response=?res); let response: payu::PayuErrorResponse = res .response .parse_struct("Payu ErrorResponse") @@ -85,23 +97,15 @@ impl ConnectorCommon for Payu { impl api::Payment for Payu {} impl api::PreVerify for Payu {} -impl - services::ConnectorIntegration< - api::Verify, - types::VerifyRequestData, - types::PaymentsResponseData, - > for Payu +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Payu { } impl api::PaymentVoid for Payu {} -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Payu +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Payu { fn get_headers( &self, @@ -124,7 +128,7 @@ impl Ok(format!( "{}{}{}", self.base_url(connectors), - "v2_1/orders/", + "api/v2_1/orders/", connector_payment_id )) } @@ -167,18 +171,106 @@ impl impl api::ConnectorAccessToken for Payu {} -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Payu +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Payu { + fn get_url( + &self, + _req: &types::RefreshTokenRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "pl/standard/user/oauth/authorize" + )) + } + + fn get_content_type(&self) -> &'static str { + "application/x-www-form-urlencoded" + } + + fn get_headers( + &self, + _req: &types::RefreshTokenRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + types::RefreshTokenType::get_content_type(self).to_string(), + )]) + } + + fn get_request_body( + &self, + req: &types::RefreshTokenRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let payu_req = utils::Encode::<payu::PayuAuthUpdateRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + logger::debug!(payu_access_token_request=?payu_req); + Ok(Some(payu_req)) + } + + fn build_request( + &self, + req: &types::RefreshTokenRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let req = Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .headers(types::RefreshTokenType::get_headers(self, req, connectors)?) + .url(&types::RefreshTokenType::get_url(self, req, connectors)?) + .body(types::RefreshTokenType::get_request_body(self, req)?) + .build(), + ); + + logger::debug!(payu_access_token_request=?req); + + Ok(req) + } + fn handle_response( + &self, + data: &types::RefreshTokenRouterData, + res: types::Response, + ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { + logger::debug!(access_token_response=?res); + let response: payu::PayuAuthUpdateResponse = res + .response + .parse_struct("payu PayuAuthUpdateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + logger::debug!(access_token_error_response=?res); + let response: payu::PayuAccessTokenErrorResponse = res + .response + .parse_struct("Payu AccessTokenErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.error, + message: response.error_description, + reason: None, + }) + } } impl api::PaymentSync for Payu {} -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Payu { fn get_headers( @@ -206,7 +298,7 @@ impl Ok(format!( "{}{}{}", self.base_url(connectors), - "v2_1/orders/", + "api/v2_1/orders/", connector_payment_id )) } @@ -253,12 +345,8 @@ impl } impl api::PaymentCapture for Payu {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Payu +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Payu { fn get_headers( &self, @@ -280,7 +368,7 @@ impl Ok(format!( "{}{}{}{}", self.base_url(connectors), - "v2_1/orders/", + "api/v2_1/orders/", req.request.connector_transaction_id, "/status" )) @@ -343,24 +431,16 @@ impl impl api::PaymentSession for Payu {} -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Payu +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Payu { //TODO: implement sessions flow } impl api::PaymentAuthorize for Payu {} -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Payu +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Payu { fn get_headers( &self, @@ -379,7 +459,11 @@ impl _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v2_1/orders")) + Ok(format!( + "{}{}", + self.base_url(connectors), + "api/v2_1/orders" + )) } fn get_request_body( @@ -447,9 +531,7 @@ impl api::Refund for Payu {} impl api::RefundExecute for Payu {} impl api::RefundSync for Payu {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Payu -{ +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payu { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, @@ -470,7 +552,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref Ok(format!( "{}{}{}{}", self.base_url(connectors), - "v2_1/orders/", + "api/v2_1/orders/", req.request.connector_transaction_id, "/refund" )) @@ -530,9 +612,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref } } -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Payu -{ +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payu { fn get_headers( &self, req: &types::RefundSyncRouterData, @@ -553,7 +633,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun Ok(format!( "{}{}{}{}", self.base_url(connectors), - "v2_1/orders/", + "api/v2_1/orders/", req.request.connector_transaction_id, "/refunds" )) diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 3f55a2b65c4..c62164af9e1 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -3,6 +3,7 @@ use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; use crate::{ + connector::utils::AccessTokenRequestInfo, consts, core::errors, pii::{self, Secret}, @@ -268,6 +269,48 @@ impl<F, T> } } +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct PayuAuthUpdateRequest { + grant_type: String, + client_id: String, + client_secret: String, +} + +impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + grant_type: "client_credentials".to_string(), + client_id: item.get_request_id()?, + client_secret: item.request.app_id.clone(), + }) + } +} +#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +pub struct PayuAuthUpdateResponse { + pub access_token: String, + pub token_type: String, + pub expires_in: i64, + pub grant_type: String, +} + +impl<F, T> TryFrom<types::ResponseRouterData<F, PayuAuthUpdateResponse, T, types::AccessToken>> + for types::RouterData<F, T, types::AccessToken> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PayuAuthUpdateResponse, T, types::AccessToken>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::AccessToken { + token: item.response.access_token, + expires: item.response.expires_in, + }), + ..item.data + }) + } +} + #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsCancelResponse { @@ -456,9 +499,9 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for PayuRefundRequest { fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { refund: PayuRefundRequestData { - description: item.description.clone().ok_or( + description: item.request.reason.clone().ok_or( errors::ConnectorError::MissingRequiredField { - field_name: "item.description".to_string(), + field_name: "item.request.reason".to_string(), }, )?, amount: None, @@ -474,6 +517,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for PayuRefundRequest { #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Finalized, + Completed, Canceled, #[default] Pending, @@ -482,7 +526,7 @@ pub enum RefundStatus { impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { - RefundStatus::Finalized => Self::Success, + RefundStatus::Finalized | RefundStatus::Completed => Self::Success, RefundStatus::Canceled => Self::Failure, RefundStatus::Pending => Self::Pending, } @@ -563,3 +607,9 @@ pub struct PayuErrorData { pub struct PayuErrorResponse { pub status: PayuErrorData, } + +#[derive(Deserialize, Debug)] +pub struct PayuAccessTokenErrorResponse { + pub error: String, + pub error_description: String, +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 4b8c095cd8b..952e788da63 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -18,6 +18,20 @@ pub fn missing_field_err( } type Error = error_stack::Report<errors::ConnectorError>; + +pub trait AccessTokenRequestInfo { + fn get_request_id(&self) -> Result<String, Error>; +} + +impl AccessTokenRequestInfo for types::RefreshTokenRouterData { + fn get_request_id(&self) -> Result<String, Error> { + self.request + .id + .clone() + .ok_or_else(missing_field_err("request.id")) + } +} + pub trait PaymentsRequestData { fn get_attempt_id(&self) -> Result<String, Error>; fn get_billing(&self) -> Result<&api::Address, Error>; diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 3a183ba830e..fb7a4ce5b85 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -1,3 +1,4 @@ +use futures::future::OptionFuture; use masking::Secret; use router::types::{self, api, storage::enums}; use serde_json::json; @@ -79,52 +80,78 @@ async fn should_authorize_and_capture_payment() { assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } -// You get a service declined for Payment Capture, look into it from merchant dashboard -/* #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Fiserv {}; - let authorize_response = connector.authorize_payment(None, None).await; + let authorize_response = connector + .authorize_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4005550000000019".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2035".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("123".to_string()), + }), + capture_method: Some(storage_models::enums::CaptureMethod::Manual), + ..utils::PaymentAuthorizeType::default().0 + }), + None, + ) + .await + .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { - connector.capture_payment(transaction_id, None, None).await.status + connector + .capture_payment(transaction_id, None, None) + .await + .unwrap() + .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); } #[actix_web::test] -async fn should_fail_payment_for_incorrect_cvc() { - let response = Fiserv {}.make_payment(Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethod::Card(api::CCard { - card_number: Secret::new("4024007134364842".to_string()), - ..utils::CCardType::default().0 +async fn should_fail_payment_for_missing_cvc() { + let response = Fiserv {} + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethod::Card(api::CCard { + card_number: Secret::new("4005550000000019".to_string()), + card_exp_month: Secret::new("02".to_string()), + card_exp_year: Secret::new("2035".to_string()), + card_holder_name: Secret::new("John Doe".to_string()), + card_cvc: Secret::new("".to_string()), + }), + ..utils::PaymentAuthorizeType::default().0 }), - ..utils::PaymentAuthorizeType::default().0 - }), None) - .await; + None, + ) + .await + .unwrap(); let x = response.response.unwrap_err(); - assert_eq!( - x.message, - "The card's security code failed verification.".to_string(), - ); + assert_eq!(x.message, "Invalid or Missing Field Data".to_string(),); } +#[ignore] #[actix_web::test] async fn should_refund_succeeded_payment() { let connector = Fiserv {}; //make a successful payment - let response = connector.make_payment(None, None).await; + let response = connector.make_payment(None, None).await.unwrap(); //try refund for previous payment if let Some(transaction_id) = utils::get_connector_transaction_id(response) { - let response = connector.refund_payment(transaction_id, None, None).await; + let response = connector + .refund_payment(transaction_id, None, None) + .await + .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } -*/ diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index d2b1f3387da..31104d9aeb1 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -56,6 +56,7 @@ fn get_default_payment_info() -> Option<PaymentInfo> { ..Default::default() }), auth_type: None, + access_token: None, }) } diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index f13bdf9f112..d610119a658 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -1,13 +1,12 @@ -use router::types::{self, api, storage::enums}; +use router::types::{self, api, storage::enums, AccessToken, ConnectorAuthType}; use crate::{ connector_auth, - utils::{self, ConnectorActions, PaymentAuthorizeType}, + utils::{self, Connector, ConnectorActions, PaymentAuthorizeType}, }; - struct Payu; impl ConnectorActions for Payu {} -impl utils::Connector for Payu { +impl Connector for Payu { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payu; types::api::ConnectorData { @@ -17,7 +16,7 @@ impl utils::Connector for Payu { } } - fn get_auth_token(&self) -> types::ConnectorAuthType { + fn get_auth_token(&self) -> ConnectorAuthType { types::ConnectorAuthType::from( connector_auth::ConnectorAuthentication::new() .payu @@ -30,7 +29,26 @@ impl utils::Connector for Payu { } } +fn get_access_token() -> Option<AccessToken> { + let connector = Payu {}; + match connector.get_auth_token() { + ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken { + token: api_key, + expires: key1.parse::<i64>().unwrap(), + }), + _ => None, + } +} +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + Some(utils::PaymentInfo { + address: None, + auth_type: None, + access_token: get_access_token(), + }) +} + #[actix_web::test] +#[ignore] async fn should_authorize_card_payment() { //Authorize Card Payment in PLN currency let authorize_response = Payu {} @@ -39,7 +57,7 @@ async fn should_authorize_card_payment() { currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -47,7 +65,8 @@ async fn should_authorize_card_payment() { assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { let sync_response = Payu {} - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id.clone(), @@ -55,7 +74,7 @@ async fn should_authorize_card_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -74,7 +93,7 @@ async fn should_authorize_gpay_payment() { }), currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 - }), None).await.unwrap(); + }), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { let sync_response = Payu {} @@ -86,7 +105,7 @@ async fn should_authorize_gpay_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -95,6 +114,7 @@ async fn should_authorize_gpay_payment() { } #[actix_web::test] +#[ignore] async fn should_capture_already_authorized_payment() { let connector = Payu {}; let authorize_response = connector @@ -103,15 +123,15 @@ async fn should_capture_already_authorized_payment() { currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 }), - None, + get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); - if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { let sync_response = connector - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id.clone(), @@ -119,18 +139,19 @@ async fn should_capture_already_authorized_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = connector - .capture_payment(transaction_id.clone(), None, None) + .capture_payment(transaction_id.clone(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Pending); let response = connector - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id, @@ -138,7 +159,7 @@ async fn should_capture_already_authorized_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -147,6 +168,7 @@ async fn should_capture_already_authorized_payment() { } #[actix_web::test] +#[ignore] async fn should_sync_payment() { let connector = Payu {}; // Authorize the payment for manual capture @@ -156,7 +178,7 @@ async fn should_sync_payment() { currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -165,7 +187,8 @@ async fn should_sync_payment() { if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { // Sync the Payment Data let response = connector - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id, @@ -173,7 +196,7 @@ async fn should_sync_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -183,6 +206,7 @@ async fn should_sync_payment() { } #[actix_web::test] +#[ignore] async fn should_void_already_authorized_payment() { let connector = Payu {}; //make a successful payment @@ -192,7 +216,7 @@ async fn should_void_already_authorized_payment() { currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -201,13 +225,14 @@ async fn should_void_already_authorized_payment() { //try CANCEL for previous payment if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { let void_response = connector - .void_payment(transaction_id.clone(), None, None) + .void_payment(transaction_id.clone(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::Pending); let sync_response = connector - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Voided, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id, @@ -215,7 +240,7 @@ async fn should_void_already_authorized_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); @@ -224,31 +249,47 @@ async fn should_void_already_authorized_payment() { } #[actix_web::test] +#[ignore] async fn should_refund_succeeded_payment() { let connector = Payu {}; - //make a successful payment let authorize_response = connector - .make_payment( + .authorize_payment( Some(types::PaymentsAuthorizeData { currency: enums::Currency::PLN, ..PaymentAuthorizeType::default().0 }), - None, + get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response) { + let sync_response = connector + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + transaction_id.clone(), + ), + encoded_data: None, + capture_method: None, + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); //Capture the payment in case of Manual Capture let capture_response = connector - .capture_payment(transaction_id.clone(), None, None) + .capture_payment(transaction_id.clone(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Pending); let sync_response = connector - .sync_payment( + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( transaction_id.clone(), @@ -256,15 +297,14 @@ async fn should_refund_succeeded_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Charged); - //Refund the payment let refund_response = connector - .refund_payment(transaction_id.clone(), None, None) + .refund_payment(transaction_id.clone(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( @@ -280,7 +320,11 @@ async fn should_sync_succeeded_refund_payment() { //Currently hardcoding the order_id because RSync is not instant, change it accordingly let sync_refund_response = connector - .sync_refund("6DHQQN3T57230110GUEST000P01".to_string(), None, None) + .sync_refund( + "6DHQQN3T57230110GUEST000P01".to_string(), + None, + get_default_payment_info(), + ) .await .unwrap(); assert_eq!( @@ -294,7 +338,11 @@ async fn should_fail_already_refunded_payment() { let connector = Payu {}; //Currently hardcoding the order_id, change it accordingly let response = connector - .refund_payment("5H1SVX6P7W230112GUEST000P01".to_string(), None, None) + .refund_payment( + "5H1SVX6P7W230112GUEST000P01".to_string(), + None, + get_default_payment_info(), + ) .await .unwrap(); let x = response.response.unwrap_err(); diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 0fd79e47c20..9b442f770c2 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1,13 +1,13 @@ -use std::{fmt::Debug, marker::PhantomData}; +use std::{fmt::Debug, marker::PhantomData, thread::sleep, time::Duration}; use async_trait::async_trait; use error_stack::Report; use masking::Secret; use router::{ - core::{errors::ConnectorError, payments}, + core::{errors, errors::ConnectorError, payments}, db::StorageImpl, routes, services, - types::{self, api, storage::enums, PaymentAddress}, + types::{self, api, storage::enums, AccessToken, PaymentAddress}, }; use wiremock::{Mock, MockServer}; @@ -24,6 +24,7 @@ pub trait Connector { pub struct PaymentInfo { pub address: Option<PaymentAddress>, pub auth_type: Option<enums::AuthenticationType>, + pub access_token: Option<AccessToken>, } #[async_trait] @@ -69,6 +70,29 @@ pub trait ConnectorActions: Connector { call_connector(request, integration).await } + /// will retry the psync till the given status matches or retry max 3 times in a 10secs interval + async fn psync_retry_till_status_matches( + &self, + status: enums::AttemptStatus, + payment_data: Option<types::PaymentsSyncData>, + payment_info: Option<PaymentInfo>, + ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { + let max_try = 3; + let mut curr_try = 1; + while curr_try <= max_try { + let sync_res = self + .sync_payment(payment_data.clone(), payment_info.clone()) + .await + .unwrap(); + if (sync_res.status == status) || (curr_try == max_try) { + return Ok(sync_res); + } + sleep(Duration::from_secs(10)); + curr_try += 1; + } + Err(errors::ConnectorError::ProcessingStepFailed(None).into()) + } + async fn capture_payment( &self, transaction_id: String, @@ -120,7 +144,7 @@ pub trait ConnectorActions: Connector { connector_transaction_id: transaction_id, refund_amount: 100, connector_metadata: None, - reason: None, + reason: Some("Customer returned product".to_string()), }), payment_info, ); @@ -175,10 +199,14 @@ pub trait ConnectorActions: Connector { request: req, response: Err(types::ErrorResponse::default()), payment_method_id: None, - address: info.map_or(PaymentAddress::default(), |a| a.address.unwrap()), + address: info + .clone() + .and_then(|a| a.address) + .or_else(|| Some(PaymentAddress::default())) + .unwrap(), connector_meta_data: self.get_connector_meta(), amount_captured: None, - access_token: None, + access_token: info.and_then(|a| a.access_token), } } } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 7aad7366a57..15092018814 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -50,6 +50,7 @@ impl WorldlineTest { ..Default::default() }), auth_type: None, + access_token: None, }) }
feat
add auth_token_refresh for payu and some quick bug fixes (#426)
b5ea8db2d2b7e7544931704a7191b42d3a8299be
2023-11-10 16:38:30
Swangi Kumari
refactor(connector): [Zen] change error message from NotSupported to NotImplemented (#2831)
false
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index d13c9b6421f..6b0d46dec8d 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -290,10 +290,9 @@ impl | api_models::payments::VoucherData::FamilyMart { .. } | api_models::payments::VoucherData::Seicomart { .. } | api_models::payments::VoucherData::PayEasy { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ))? } }; Ok(Self::ApiRequest(Box::new(ApiRequest { @@ -342,12 +341,8 @@ impl api_models::payments::BankTransferData::Pse { .. } => { ZenPaymentChannels::PclBoacompraPse } - api_models::payments::BankTransferData::SepaBankTransfer { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Zen"), - ))? - } - api_models::payments::BankTransferData::AchBankTransfer { .. } + api_models::payments::BankTransferData::SepaBankTransfer { .. } + | api_models::payments::BankTransferData::AchBankTransfer { .. } | api_models::payments::BankTransferData::BacsBankTransfer { .. } | api_models::payments::BankTransferData::PermataBankTransfer { .. } | api_models::payments::BankTransferData::BcaBankTransfer { .. } @@ -356,10 +351,9 @@ impl | api_models::payments::BankTransferData::CimbVaBankTransfer { .. } | api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } | api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ))? } }; Ok(Self::ApiRequest(Box::new(ApiRequest { @@ -489,12 +483,8 @@ impl api_models::payments::WalletData::WeChatPayRedirect(_) | api_models::payments::WalletData::PaypalRedirect(_) | api_models::payments::WalletData::ApplePay(_) - | api_models::payments::WalletData::GooglePay(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Zen"), - ))? - } - api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::GooglePay(_) + | api_models::payments::WalletData::AliPayQr(_) | api_models::payments::WalletData::AliPayRedirect(_) | api_models::payments::WalletData::AliPayHkRedirect(_) | api_models::payments::WalletData::MomoRedirect(_) @@ -514,10 +504,9 @@ impl | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) | api_models::payments::WalletData::WeChatPayQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ))? } }; let terminal_uuid = session_data @@ -719,10 +708,9 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment | api_models::payments::PaymentMethodData::MandatePayment | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ))? } } } @@ -736,13 +724,8 @@ impl TryFrom<&api_models::payments::BankRedirectData> for ZenPaymentsRequest { | api_models::payments::BankRedirectData::Sofort { .. } | api_models::payments::BankRedirectData::BancontactCard { .. } | api_models::payments::BankRedirectData::Blik { .. } - | api_models::payments::BankRedirectData::Trustly { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Zen"), - ) - .into()) - } - api_models::payments::BankRedirectData::Eps { .. } + | api_models::payments::BankRedirectData::Trustly { .. } + | api_models::payments::BankRedirectData::Eps { .. } | api_models::payments::BankRedirectData::Giropay { .. } | api_models::payments::BankRedirectData::Przelewy24 { .. } | api_models::payments::BankRedirectData::Bizum {} @@ -754,10 +737,9 @@ impl TryFrom<&api_models::payments::BankRedirectData> for ZenPaymentsRequest { | api_models::payments::BankRedirectData::OpenBankingUk { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ) .into()) } } @@ -776,10 +758,9 @@ impl TryFrom<&api_models::payments::PayLaterData> for ZenPaymentsRequest { | api_models::payments::PayLaterData::WalleyRedirect {} | api_models::payments::PayLaterData::AlmaRedirect {} | api_models::payments::PayLaterData::AtomeRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ) .into()) } } @@ -794,10 +775,9 @@ impl TryFrom<&api_models::payments::BankDebitData> for ZenPaymentsRequest { | api_models::payments::BankDebitData::SepaBankDebit { .. } | api_models::payments::BankDebitData::BecsBankDebit { .. } | api_models::payments::BankDebitData::BacsBankDebit { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ) .into()) } } @@ -811,10 +791,9 @@ impl TryFrom<&api_models::payments::CardRedirectData> for ZenPaymentsRequest { api_models::payments::CardRedirectData::Knet {} | api_models::payments::CardRedirectData::Benefit {} | api_models::payments::CardRedirectData::MomoAtm {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Zen"), + ) .into()) } } @@ -825,19 +804,13 @@ impl TryFrom<&api_models::payments::GiftCardData> for ZenPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> { match value { - api_models::payments::GiftCardData::PaySafeCard {} => { + api_models::payments::GiftCardData::PaySafeCard {} + | api_models::payments::GiftCardData::Givex(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), ) .into()) } - api_models::payments::GiftCardData::Givex(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Zen", - } - .into()) - } } } }
refactor
[Zen] change error message from NotSupported to NotImplemented (#2831)
6d9b37e8a2e91a0cf2e493dd48100bfeebadd926
2024-06-28 13:17:21
Apoorv Dixit
fix(users): clear cookie and alter parsing for sso (#5147)
false
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 3e9145c2d33..ff1477aa3c9 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -4,7 +4,6 @@ use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse}, }; -use common_utils::ext_traits::ValueExt; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ @@ -481,7 +480,7 @@ pub async fn rotate_password( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } #[cfg(feature = "email")] @@ -544,7 +543,7 @@ pub async fn reset_password_token_only_flow( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } #[cfg(feature = "email")] @@ -597,7 +596,7 @@ pub async fn reset_password( .await .map_err(|e| logger::error!(?e)); - Ok(ApplicationResponse::StatusOk) + auth::cookies::remove_cookie_response() } pub async fn invite_multiple_user( @@ -2174,10 +2173,10 @@ pub async fn list_user_authentication_methods( .map(|auth_method| { let auth_name = match (auth_method.auth_type, auth_method.public_config) { (common_enums::UserAuthType::OpenIdConnect, Some(config)) => { - let open_id_public_config: user_api::OpenIdConnectPublicConfig = config - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse generic data value")?; + let open_id_public_config = + serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(config) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; Ok(Some(open_id_public_config.name)) } @@ -2216,13 +2215,14 @@ pub async fn get_sso_auth_url( utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) .await?; - let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method - .public_config - .ok_or(UserErrors::InternalServerError) - .attach_printable("Public config not present")? - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( + user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")?, + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let oidc_state = Secret::new(nanoid::nanoid!()); utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?; @@ -2267,13 +2267,14 @@ pub async fn sso_sign( utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) .await?; - let open_id_public_config: user_api::OpenIdConnectPublicConfig = user_authentication_method - .public_config - .ok_or(UserErrors::InternalServerError) - .attach_printable("Public config not present")? - .parse_value("OpenIdConnectPublicConfig") - .change_context(UserErrors::InternalServerError) - .attach_printable("unable to parse OpenIdConnectPublicConfig")?; + let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( + user_authentication_method + .public_config + .ok_or(UserErrors::InternalServerError) + .attach_printable("Public config not present")?, + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let redirect_url = utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); @@ -2329,14 +2330,14 @@ pub async fn terminate_auth_select( .store .get_user_authentication_method_by_id(&req.id) .await - .change_context(UserErrors::InternalServerError)?; + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; // Skip SSO if continue with password(TOTP) if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && user_authentication_method.auth_type != common_enums::UserAuthType::OpenIdConnect + && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) { next_flow = next_flow.skip(user_from_db, &state).await?; } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 6b957281f76..e80fe8d1de8 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,7 +1,8 @@ use std::{collections::HashMap, sync::Arc}; use api_models::user as user_api; -use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use common_enums::UserAuthType; +use common_utils::errors::CustomResult; use diesel_models::{encryption::Encryption, enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; @@ -206,7 +207,7 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .attach_printable("Failed to get redis connection") } -impl ForeignFrom<user_api::AuthConfig> for common_enums::UserAuthType { +impl ForeignFrom<user_api::AuthConfig> for UserAuthType { fn foreign_from(from: user_api::AuthConfig) -> Self { match from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, @@ -244,8 +245,7 @@ pub async fn decrypt_oidc_private_config( .into_inner() .expose(); - private_config - .parse_value("OpenIdConnectPrivateConfig") + serde_json::from_value::<user_api::OpenIdConnectPrivateConfig>(private_config) .change_context(UserErrors::InternalServerError) .attach_printable("unable to parse OpenIdConnectPrivateConfig") } @@ -286,3 +286,10 @@ fn get_oidc_key(oidc_state: &str) -> String { pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } + +pub fn is_sso_auth_type(auth_type: &UserAuthType) -> bool { + match auth_type { + UserAuthType::OpenIdConnect => true, + UserAuthType::Password | UserAuthType::MagicLink => false, + } +}
fix
clear cookie and alter parsing for sso (#5147)
902a8b5ee9bd4e689bdaea090907697a91fc8c51
2023-01-16 18:50:13
Rachit Naithani
chore(router): add JWT to OLAP routes (#386)
false
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 7e14ec2eb56..fa2f95f06f6 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -32,7 +32,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req| create_merchant_account(&*state.store, req), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -53,7 +53,7 @@ pub async fn retrieve_merchant_account( &req, payload, |state, _, req| get_merchant_account(&*state.store, req), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -72,7 +72,7 @@ pub async fn update_merchant_account( &req, json_payload.into_inner(), |state, _, req| merchant_account_update(&*state.store, &merchant_id, req), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -93,7 +93,7 @@ pub async fn delete_merchant_account( &req, payload, |state, _, req| merchant_account_delete(&*state.store, req.merchant_id), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -113,7 +113,7 @@ pub async fn payment_connector_create( &req, json_payload.into_inner(), |state, _, req| create_payment_connector(&*state.store, req, &merchant_id), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -138,7 +138,7 @@ pub async fn payment_connector_retrieve( |state, _, req| { retrieve_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) }, - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -156,7 +156,7 @@ pub async fn payment_connector_list( &req, merchant_id, |state, _, merchant_id| list_payment_connectors(&*state.store, merchant_id), - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -177,7 +177,7 @@ pub async fn payment_connector_update( |state, _, req| { update_payment_connector(&*state.store, &merchant_id, merchant_connector_id, req) }, - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } @@ -202,7 +202,7 @@ pub async fn payment_connector_delete( |state, _, req| { delete_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) }, - &auth::AdminApiAuth, + *auth::jwt_auth_or(&auth::AdminApiAuth, req.headers()), ) .await } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 81038c41931..c4c2b46d452 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -105,7 +105,7 @@ pub async fn get_customer_mandates( |state, merchant_account, req| { crate::core::mandate::get_customer_mandates(state, merchant_account, req) }, - &auth::ApiKeyAuth, + *auth::jwt_auth_or(&auth::ApiKeyAuth, req.headers()), ) .await } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 106a4cc785d..f08eadede28 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -337,7 +337,7 @@ pub async fn payments_list( |state, merchant_account, req| { payments::list_payments(&*state.store, merchant_account, req) }, - &auth::ApiKeyAuth, + *auth::jwt_auth_or(&auth::ApiKeyAuth, req.headers()), ) .await } diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index ff7b3c14ac2..f627c2baddb 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -92,7 +92,7 @@ pub async fn refunds_list( &req, payload.into_inner(), |state, merchant_account, req| refund_list(&*state.store, merchant_account, req), - &auth::ApiKeyAuth, + *auth::jwt_auth_or(&auth::ApiKeyAuth, req.headers()), ) .await } diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index e62841a3031..583eb07f8a8 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -105,6 +105,25 @@ impl AuthenticateAndFetch<storage::MerchantAccount> for PublishableKeyAuth { #[derive(Debug)] pub struct JWTAuth; +#[derive(serde::Deserialize)] +struct JwtAuthPayloadFetchUnit { + #[serde(rename(deserialize = "exp"))] + _exp: u64, +} + +#[async_trait] +impl AuthenticateAndFetch<()> for JWTAuth { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<()> { + let mut token = get_jwt(request_headers)?; + token = strip_jwt_token(token)?; + decode_jwt::<JwtAuthPayloadFetchUnit>(token, state).map(|_| ()) + } +} + #[derive(serde::Deserialize)] struct JwtAuthPayloadFetchMerchantAccount { merchant_id: String, @@ -144,17 +163,17 @@ impl ClientSecretFetch for ListPaymentMethodRequest { } } -pub fn jwt_auth_or<T>( +pub fn jwt_auth_or<'a, T>( + default_auth: &'a dyn AuthenticateAndFetch<T>, headers: &HeaderMap, - default_auth: Box<dyn AuthenticateAndFetch<T>>, -) -> Box<dyn AuthenticateAndFetch<T>> +) -> Box<&'a dyn AuthenticateAndFetch<T>> where JWTAuth: AuthenticateAndFetch<T>, { if is_jwt_auth(headers) { - return Box::new(JWTAuth); + return Box::new(&JWTAuth); } - default_auth + Box::new(default_auth) } pub fn get_auth_type_and_flow(
chore
add JWT to OLAP routes (#386)
ed99655ebc11d53f4b2ffcb8c0eb9ef6b56f32c4
2023-05-03 15:48:51
Manoj Ghorela
feat: PG Agnostic mandate using network_txns_id (Adyen, Authorizedotnet, Stripe) (#855)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8cd2a0c329d..de0cd91e527 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -302,14 +302,20 @@ pub enum MandateTxnType { #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: String, - pub connector_mandate_id: Option<String>, + pub mandate_reference_id: Option<MandateReferenceId>, +} + +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub enum MandateReferenceId { + ConnectorMandateId(String), // mandate_id send by connector + NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id, - connector_mandate_id: None, + mandate_reference_id: None, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 4955f437aa6..243b05e2c45 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -65,12 +65,33 @@ pub struct Settings { #[cfg(feature = "s3")] pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, + pub connector_customer: ConnectorCustomer, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>); +#[derive(Debug, Deserialize, Clone, Default)] +pub struct ConnectorCustomer { + #[serde(deserialize_with = "connector_deser")] + pub connector_list: HashSet<api_models::enums::Connector>, +} + +fn connector_deser<'a, D>( + deserializer: D, +) -> Result<HashSet<api_models::enums::Connector>, D::Error> +where + D: Deserializer<'a>, +{ + let value = <String>::deserialize(deserializer)?; + Ok(value + .trim() + .split(',') + .flat_map(api_models::enums::Connector::from_str) + .collect()) +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "pm_deser")] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 01637c3b30a..7ac9e430311 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -337,6 +337,7 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 5c9c85a789e..72ae3d0e5d1 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,11 +1,13 @@ -use api_models::{enums::DisputeStage, webhooks::IncomingWebhookEvent}; +use api_models::{ + enums::DisputeStage, payments::MandateReferenceId, webhooks::IncomingWebhookEvent, +}; use masking::PeekInterface; use reqwest::Url; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, consts, core::errors, pii::{self, Email, Secret}, @@ -37,18 +39,24 @@ pub enum AdyenShopperInteraction { #[serde(rename_all = "camelCase")] pub enum AdyenRecurringModel { UnscheduledCardOnFile, + CardOnFile, } -#[derive(Default, Debug, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, Serialize, Deserialize)] pub enum AuthType { #[default] PreAuth, } -#[derive(Default, Debug, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalData { - authorisation_type: AuthType, - manual_capture: bool, + authorisation_type: Option<AuthType>, + manual_capture: Option<bool>, + #[serde(rename = "recurring.recurringDetailReference")] + recurring_detail_reference: Option<String>, + #[serde(rename = "recurring.shopperReference")] + recurring_shopper_reference: Option<String>, + network_tx_reference: Option<String>, } #[derive(Debug, Serialize)] @@ -93,6 +101,8 @@ pub struct AdyenPaymentRequest<'a> { #[serde(skip_serializing_if = "Option::is_none")] recurring_processing_model: Option<AdyenRecurringModel>, additional_data: Option<AdditionalData>, + shopper_reference: Option<String>, + store_payment_method: Option<bool>, shopper_name: Option<ShopperName>, shopper_locale: Option<String>, shopper_email: Option<Secret<String, Email>>, @@ -200,6 +210,7 @@ pub struct AdyenResponse { merchant_reference: String, refusal_reason: Option<String>, refusal_reason_code: Option<String>, + additional_data: Option<AdditionalData>, } #[derive(Debug, Clone, Deserialize)] @@ -252,6 +263,7 @@ pub enum AdyenPaymentMethod<'a> { Giropay(Box<BankRedirectionPMData>), Gpay(Box<AdyenGPay>), Ideal(Box<BankRedirectionWithIssuer<'a>>), + Mandate(Box<AdyenMandate>), Mbway(Box<MbwayData>), MobilePay(Box<MobilePayData>), OnlineBankingCzechRepublic(Box<OnlineBankingCzechRepublicData>), @@ -484,6 +496,14 @@ pub struct BankRedirectionWithIssuer<'a> { issuer: &'a str, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenMandate { + #[serde(rename = "type")] + payment_type: PaymentType, + stored_payment_method_id: String, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCard { @@ -493,6 +513,16 @@ pub struct AdyenCard { expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Option<Secret<String>>, + brand: Option<CardBrand>, //Mandatory for mandate using network_txns_id + network_payment_reference: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CardBrand { + Visa, + MC, + Amex, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -603,6 +633,8 @@ pub enum PaymentType { Scheme, #[serde(rename = "directEbanking")] Sofort, + #[serde(rename = "networkToken")] + NetworkToken, Trustly, Walley, #[serde(rename = "wechatpayWeb")] @@ -690,24 +722,33 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { impl<'a> TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest<'a> { type Error = Error; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { - api_models::payments::PaymentMethodData::Card(ref card) => { - AdyenPaymentRequest::try_from((item, card)) - } - api_models::payments::PaymentMethodData::Wallet(ref wallet) => { - AdyenPaymentRequest::try_from((item, wallet)) - } - api_models::payments::PaymentMethodData::PayLater(ref pay_later) => { - AdyenPaymentRequest::try_from((item, pay_later)) - } - api_models::payments::PaymentMethodData::BankRedirect(ref bank_redirect) => { - AdyenPaymentRequest::try_from((item, bank_redirect)) - } - _ => Err(errors::ConnectorError::NotSupported { - payment_method: format!("{:?}", item.request.payment_method_type), - connector: "Adyen", - payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), - })?, + match item + .request + .mandate_id + .to_owned() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id) + { + Some(mandate_ref) => AdyenPaymentRequest::try_from((item, mandate_ref)), + None => match item.request.payment_method_data { + api_models::payments::PaymentMethodData::Card(ref card) => { + AdyenPaymentRequest::try_from((item, card)) + } + api_models::payments::PaymentMethodData::Wallet(ref wallet) => { + AdyenPaymentRequest::try_from((item, wallet)) + } + api_models::payments::PaymentMethodData::PayLater(ref pay_later) => { + AdyenPaymentRequest::try_from((item, pay_later)) + } + api_models::payments::PaymentMethodData::BankRedirect(ref bank_redirect) => { + AdyenPaymentRequest::try_from((item, bank_redirect)) + } + _ => Err(errors::ConnectorError::NotSupported { + payment_method: format!("{:?}", item.request.payment_method_type), + connector: "Adyen", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })?, + }, } } } @@ -720,15 +761,22 @@ impl From<&types::PaymentsAuthorizeRouterData> for AdyenShopperInteraction { } } } +type RecurringDetails = (Option<AdyenRecurringModel>, Option<bool>, Option<String>); fn get_recurring_processing_model( item: &types::PaymentsAuthorizeRouterData, -) -> Option<AdyenRecurringModel> { +) -> Result<RecurringDetails, Error> { match item.request.setup_future_usage { Some(storage_enums::FutureUsage::OffSession) => { - Some(AdyenRecurringModel::UnscheduledCardOnFile) + let customer_id = item.get_customer_id()?; + let shopper_reference = format!("{}_{}", item.merchant_id, customer_id); + Ok(( + Some(AdyenRecurringModel::UnscheduledCardOnFile), + Some(true), + Some(shopper_reference), + )) } - _ => None, + _ => Ok((None, None, None)), } } @@ -757,8 +805,11 @@ fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<AdyenBr fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> { match item.request.capture_method { Some(storage_models::enums::CaptureMethod::Manual) => Some(AdditionalData { - authorisation_type: AuthType::PreAuth, - manual_capture: true, + authorisation_type: Some(AuthType::PreAuth), + manual_capture: Some(true), + network_tx_reference: None, + recurring_detail_reference: None, + recurring_shopper_reference: None, }), _ => None, } @@ -843,11 +894,25 @@ impl<'a> TryFrom<&api::Card> for AdyenPaymentMethod<'a> { expiry_month: card.card_exp_month.clone(), expiry_year: card.card_exp_year.clone(), cvc: Some(card.card_cvc.clone()), + brand: None, + network_payment_reference: None, }; Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card))) } } +impl TryFrom<&utils::CardIssuer> for CardBrand { + type Error = Error; + fn try_from(card_issuer: &utils::CardIssuer) -> Result<Self, Self::Error> { + match card_issuer { + utils::CardIssuer::AmericanExpress => Ok(Self::Amex), + utils::CardIssuer::Master => Ok(Self::MC), + utils::CardIssuer::Visa => Ok(Self::Visa), + _ => Err(errors::ConnectorError::NotImplemented("CardBrand".to_string()).into()), + } + } +} + impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { type Error = Error; fn try_from(wallet_data: &api::WalletData) -> Result<Self, Self::Error> { @@ -1022,6 +1087,81 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod } } +impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> + for AdyenPaymentRequest<'a> +{ + type Error = Error; + fn try_from( + value: (&types::PaymentsAuthorizeRouterData, MandateReferenceId), + ) -> Result<Self, Self::Error> { + let (item, mandate_ref_id) = value; + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let (recurring_processing_model, store_payment_method, shopper_reference) = + get_recurring_processing_model(item)?; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let return_url = item.request.get_return_url()?; + let payment_method = match mandate_ref_id { + MandateReferenceId::ConnectorMandateId(connector_mandate_id) => { + let adyen_mandate = AdyenMandate { + payment_type: PaymentType::Scheme, + stored_payment_method_id: connector_mandate_id, + }; + Ok::<AdyenPaymentMethod<'_>, Self::Error>(AdyenPaymentMethod::Mandate(Box::new( + adyen_mandate, + ))) + } + MandateReferenceId::NetworkMandateId(network_mandate_id) => { + match item.request.payment_method_data { + api::PaymentMethodData::Card(ref card) => { + let card_issuer = card.get_card_issuer()?; + let brand = CardBrand::try_from(&card_issuer)?; + let adyen_card = AdyenCard { + payment_type: PaymentType::Scheme, + number: card.card_number.clone(), + expiry_month: card.card_exp_month.clone(), + expiry_year: card.card_exp_year.clone(), + cvc: None, + brand: Some(brand), + network_payment_reference: Some(network_mandate_id), + }; + Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card))) + } + _ => Err(errors::ConnectorError::NotSupported { + payment_method: format!("mandate_{:?}", item.payment_method), + connector: "Adyen", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })?, + } + } + }?; + Ok(AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + shopper_interaction, + recurring_processing_model, + browser_info, + additional_data, + telephone_number: None, + shopper_name: None, + shopper_email: None, + shopper_locale: None, + billing_address: None, + delivery_address: None, + country_code: None, + line_items: None, + shopper_reference, + store_payment_method, + }) + } +} + impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPaymentRequest<'a> { type Error = Error; fn try_from( @@ -1031,7 +1171,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPay let amount = get_amount_data(item); let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; let shopper_interaction = AdyenShopperInteraction::from(item); - let recurring_processing_model = get_recurring_processing_model(item); + let (recurring_processing_model, store_payment_method, shopper_reference) = + get_recurring_processing_model(item)?; let browser_info = get_browser_info(item); let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; @@ -1054,6 +1195,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPay delivery_address: None, country_code: None, line_items: None, + shopper_reference, + store_payment_method, }) } } @@ -1075,7 +1218,8 @@ impl<'a> let amount = get_amount_data(item); let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; let shopper_interaction = AdyenShopperInteraction::from(item); - let recurring_processing_model = get_recurring_processing_model(item); + let (recurring_processing_model, store_payment_method, shopper_reference) = + get_recurring_processing_model(item)?; let browser_info = get_browser_info(item); let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; @@ -1101,6 +1245,8 @@ impl<'a> delivery_address: None, country_code: country, line_items, + shopper_reference, + store_payment_method, }) } } @@ -1142,7 +1288,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::WalletData)> let additional_data = get_additional_data(item); let payment_method = AdyenPaymentMethod::try_from(wallet_data)?; let shopper_interaction = AdyenShopperInteraction::from(item); - let recurring_processing_model = get_recurring_processing_model(item); + let (recurring_processing_model, store_payment_method, shopper_reference) = + get_recurring_processing_model(item)?; let return_url = item.request.get_return_url()?; Ok(AdyenPaymentRequest { amount, @@ -1162,6 +1309,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::WalletData)> delivery_address: None, country_code: None, line_items: None, + shopper_reference, + store_payment_method, }) } } @@ -1180,7 +1329,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::PayLaterData)> let additional_data = get_additional_data(item); let payment_method = AdyenPaymentMethod::try_from(paylater_data)?; let shopper_interaction = AdyenShopperInteraction::from(item); - let recurring_processing_model = get_recurring_processing_model(item); + let (recurring_processing_model, store_payment_method, shopper_reference) = + get_recurring_processing_model(item)?; let return_url = item.request.get_return_url()?; let shopper_name = get_shopper_name(item); let shopper_email = item.request.email.clone(); @@ -1207,6 +1357,8 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::PayLaterData)> delivery_address, country_code, line_items, + shopper_reference, + store_payment_method, }) } } @@ -1245,6 +1397,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -1279,12 +1432,20 @@ pub fn get_adyen_response( } else { None }; + let mandate_reference = response + .additional_data + .as_ref() + .and_then(|additional_data| additional_data.recurring_detail_reference.to_owned()); + let network_txn_id = response + .additional_data + .and_then(|additional_data| additional_data.network_tx_reference); let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference), redirection_data: None, - mandate_reference: None, + mandate_reference, connector_metadata: None, + network_txn_id, }; Ok((status, error, payments_response_data)) } @@ -1338,6 +1499,7 @@ pub fn get_redirection_response( redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, error, payments_response_data)) } @@ -1428,6 +1590,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), amount_captured, ..item.data @@ -1686,6 +1849,7 @@ impl From<AdyenNotificationRequestItemWH> for AdyenResponse { }), refusal_reason: None, refusal_reason_code: None, + additional_data: None, } } } diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 9283c7eb703..86831e592c7 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -382,6 +382,7 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index f9992431838..8f26534058c 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -3,7 +3,7 @@ use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::RefundsRequestData, + connector::utils::{CardData, RefundsRequestData}, core::errors, types::{self, api, storage::enums}, utils::OptionExt, @@ -68,34 +68,76 @@ enum PaymentDetails { BankRedirect, } -impl TryFrom<api_models::payments::PaymentMethodData> for PaymentDetails { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: api_models::payments::PaymentMethodData) -> Result<Self, Self::Error> { - match value { +fn get_pm_and_subsequent_auth_detail( + item: &types::PaymentsAuthorizeRouterData, +) -> Result< + ( + PaymentDetails, + Option<ProcessingOptions>, + Option<SubsequentAuthInformation>, + ), + error_stack::Report<errors::ConnectorError>, +> { + match item + .request + .mandate_id + .to_owned() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id) + { + Some(api_models::payments::MandateReferenceId::NetworkMandateId( + original_network_trans_id, + )) => { + let processing_options = Some(ProcessingOptions { + is_subsequent_auth: true, + }); + let subseuent_auth_info = Some(SubsequentAuthInformation { + original_network_trans_id, + reason: Reason::Resubmission, + }); + match item.request.payment_method_data { + api::PaymentMethodData::Card(ref ccard) => { + let payment_details = PaymentDetails::CreditCard(CreditCardDetails { + card_number: ccard.card_number.clone(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: None, + }); + Ok((payment_details, processing_options, subseuent_auth_info)) + } + _ => Err(errors::ConnectorError::NotSupported { + payment_method: format!("{:?}", item.request.payment_method_data), + connector: "AuthorizeDotNet", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl + .to_string(), + })?, + } + } + _ => match item.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => { - Ok(Self::CreditCard(CreditCardDetails { - card_number: ccard.card_number.clone(), - // expiration_date: format!("{expiry_year}-{expiry_month}").into(), - expiration_date: ccard - .card_exp_month - .clone() - .zip(ccard.card_exp_year.clone()) - .map(|(expiry_month, expiry_year)| format!("{expiry_year}-{expiry_month}")), - card_code: Some(ccard.card_cvc.clone()), - })) + 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()), + }), + None, + None, + )) + } + api::PaymentMethodData::PayLater(_) => Ok((PaymentDetails::Klarna, None, None)), + api::PaymentMethodData::Wallet(_) => Ok((PaymentDetails::Wallet, None, None)), + api::PaymentMethodData::BankRedirect(_) => { + Ok((PaymentDetails::BankRedirect, None, None)) } - api::PaymentMethodData::PayLater(_) => Ok(Self::Klarna), - api::PaymentMethodData::Wallet(_) => Ok(Self::Wallet), - api::PaymentMethodData::BankRedirect(_) => Ok(Self::BankRedirect), api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => { Err(errors::ConnectorError::NotSupported { - payment_method: format!("{value:?}"), + payment_method: format!("{:?}", item.request.payment_method_data), connector: "AuthorizeDotNet", payment_experience: api_models::enums::PaymentExperience::RedirectToUrl .to_string(), })? } - } + }, } } @@ -106,9 +148,36 @@ struct TransactionRequest { amount: i64, currency_code: String, payment: PaymentDetails, + processing_options: Option<ProcessingOptions>, + subsequent_auth_information: Option<SubsequentAuthInformation>, authorization_indicator_type: Option<AuthorizationIndicator>, } +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ProcessingOptions { + is_subsequent_auth: bool, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SubsequentAuthInformation { + original_network_trans_id: String, + // original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions. + reason: Reason, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum Reason { + Resubmission, + #[serde(rename = "delayedCharge")] + DelayedCharge, + Reauthorization, + #[serde(rename = "noShow")] + NoShow, +} + #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] struct AuthorizationIndicator { @@ -168,7 +237,8 @@ impl From<enums::CaptureMethod> for AuthorizationType { impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_details = PaymentDetails::try_from(item.request.payment_method_data.clone())?; + let (payment_details, processing_options, subsequent_auth_information) = + get_pm_and_subsequent_auth_detail(item)?; let authorization_indicator_type = item.request.capture_method.map(|c| AuthorizationIndicator { authorization_indicator: c.into(), @@ -178,6 +248,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest { amount: item.request.amount, payment: payment_details, currency_code: item.request.currency.to_string(), + processing_options, + subsequent_auth_information, authorization_indicator_type, }; @@ -271,6 +343,7 @@ pub struct TransactionResponse { auth_code: String, #[serde(rename = "transId")] transaction_id: String, + network_trans_id: Option<String>, pub(super) account_number: Option<String>, pub(super) errors: Option<Vec<ErrorMessage>>, } @@ -340,6 +413,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: metadata, + network_txn_id: item.response.transaction_response.network_trans_id, }), }, ..item.data @@ -616,6 +690,7 @@ impl<F, Req> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), status: payment_status, ..item.data diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 70f6d231a01..443e703e662 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -205,6 +205,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }), @@ -227,6 +228,7 @@ impl<F, T> .into_report() .change_context(errors::ConnectorError::ResponseHandlingFailed)?, ), + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index d091ccaa27b..c2f851ce61e 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -286,6 +286,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index c2ab2b9a5c9..dd9c03dafea 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -221,6 +221,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 4cad762a3d0..2e9a8f2b825 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -350,6 +350,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -377,6 +378,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -419,6 +421,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), status: response.into(), ..item.data @@ -490,6 +493,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), status, amount_captured, diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index 627ae4dadda..f3d43857ab4 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -144,6 +144,7 @@ impl<F, T> redirection_data: Some(redirection_data), mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), |context| { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index fab649e19cb..85377cc3fbf 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -317,6 +317,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), }, ..item.data @@ -380,6 +381,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 3952b57930b..c54fa3b31cf 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -271,6 +271,7 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -307,6 +308,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -340,6 +342,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -372,6 +375,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 5e5027fe421..b52f5d259b3 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -317,6 +317,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -350,6 +351,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 5276044f96f..46dcb527ea7 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -103,6 +103,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index d76b09b5ced..15f3a299d4c 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -214,6 +214,7 @@ fn get_payment_response( redirection_data, mandate_reference, connector_metadata: None, + network_txn_id: None, }), } } @@ -370,11 +371,14 @@ fn get_return_url(item: &types::PaymentsAuthorizeRouterData) -> Option<String> { type MandateDetails = (Option<Initiator>, Option<StoredCredential>, Option<String>); fn get_mandate_details(item: &types::PaymentsAuthorizeRouterData) -> Result<MandateDetails, Error> { Ok(if item.request.is_mandate_payment() { - let connector_mandate_id = item - .request - .mandate_id - .as_ref() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id.clone()); + let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| { + match mandate_ids.mandate_reference_id.clone() { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => Some(connector_mandate_id), + _ => None, + } + }); ( Some(match item.request.off_session { Some(true) => Initiator::Merchant, diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index e065014efb0..62ec396121a 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -120,6 +120,7 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), status: item.response.fraud_status.into(), ..item.data diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 4fb658cb166..1d0c8ecd529 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -333,6 +333,7 @@ impl<F, T> redirection_data: url, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 3aadcd8de6e..34663924739 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -345,7 +345,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques .request .mandate_id .clone() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id), + .and_then(|mandate_ids| match mandate_ids.mandate_reference_id { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => Some(connector_mandate_id), + _ => None, + }), days_active: Some(30), seconds_active: Some(259200), var1: None, @@ -469,6 +474,7 @@ impl<F, T> .payment_details .and_then(|payment_details| payment_details.recurring_id), connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index fadae497470..7c8db924538 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -355,6 +355,7 @@ impl<F, T> redirection_data, mandate_reference, connector_metadata: Some(connector_metadata), + network_txn_id: None, }), ..item.data }) @@ -436,6 +437,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: Some(connector_metadata), + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index cb85b337e64..b80c599db21 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1156,6 +1156,7 @@ where } else { None }, + network_txn_id: None, }) }, ..item.data diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs index cc665abe436..fa66aa5e126 100644 --- a/crates/router/src/connector/opennode.rs +++ b/crates/router/src/connector/opennode.rs @@ -27,6 +27,7 @@ impl api::Payment for Opennode {} impl api::PaymentSession for Opennode {} impl api::PaymentToken for Opennode {} impl api::ConnectorAccessToken for Opennode {} + impl api::PreVerify for Opennode {} impl api::PaymentAuthorize for Opennode {} impl api::PaymentSync for Opennode {} diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 4458b13eb04..51466eade83 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -110,6 +110,7 @@ impl<F, T> redirection_data: Some(redirection_data), mandate_reference: None, connector_metadata: None, + network_txn_id: None, }) } else { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index dd4d9b5aa39..428cc12bba4 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -127,11 +127,14 @@ fn get_transaction_type_and_stored_creds( (PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<errors::ConnectorError>, > { - let connector_mandate_id = item - .request - .mandate_id - .as_ref() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id.clone()); + let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| { + match mandate_ids.mandate_reference_id.clone() { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => Some(connector_mandate_id), + _ => None, + } + }); let (transaction_type, stored_credentials) = if is_mandate_payment(item, connector_mandate_id.as_ref()) { // Mandate payment @@ -353,6 +356,7 @@ impl<F, T> redirection_data: None, mandate_reference, connector_metadata: metadata, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 6c35996c9d8..c1115a5243a 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -385,6 +385,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: Some(connector_meta), + network_txn_id: None, }), ..item.data }) @@ -433,6 +434,7 @@ impl<F, T> ))), mandate_reference: None, connector_metadata: Some(connector_meta), + network_txn_id: None, }), ..item.data }) @@ -460,6 +462,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -547,6 +550,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> order_id: item.data.request.connector_transaction_id.clone(), psync_flow: PaypalPaymentIntent::Capture })), + network_txn_id: None, }), amount_captured: Some(amount_captured), ..item.data @@ -592,6 +596,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index b5a1cdbdd31..7e7cc8abf40 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -198,6 +198,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), amount_captured: None, ..item.data @@ -248,6 +249,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), amount_captured: None, ..item.data @@ -326,6 +328,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), amount_captured: None, ..item.data @@ -454,6 +457,7 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), amount_captured: Some( order diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 4e9de6121bc..63a00755155 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -402,6 +402,7 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ) } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 77fbe1cfe8a..4baf9882d1d 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -462,6 +462,7 @@ impl<F> .into_report() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, ), + network_txn_id: None, }), ..item.data }) @@ -500,6 +501,7 @@ impl<T, F> .map(|url| services::RedirectForm::from((url, services::Method::Get))), mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 98b5c0560ee..2f74ad756cc 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -84,6 +84,117 @@ impl // Not Implemented (R) } +impl api::ConnectorCustomer for Stripe {} + +impl + services::ConnectorIntegration< + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > for Stripe +{ + fn get_headers( + &self, + req: &types::ConnectorCustomerRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::ConnectorCustomerType::get_content_type(self).to_string(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::ConnectorCustomerRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}{}", self.base_url(connectors), "v1/customers")) + } + + fn get_request_body( + &self, + req: &types::ConnectorCustomerRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let connector_request = stripe::CustomerRequest::try_from(req)?; + let stripe_req = utils::Encode::<stripe::CustomerRequest>::url_encode(&connector_request) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(Some(stripe_req)) + } + + fn build_request( + &self, + req: &types::ConnectorCustomerRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::ConnectorCustomerType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::ConnectorCustomerType::get_headers( + self, req, connectors, + )?) + .body(types::ConnectorCustomerType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::ConnectorCustomerRouterData, + res: types::Response, + ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> + where + types::PaymentsResponseData: Clone, + { + let response: stripe::StripeCustomerResponse = res + .response + .parse_struct("StripeCustomerResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: stripe::ErrorResponse = res + .response + .parse_struct("ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(types::ErrorResponse { + status_code: res.status_code, + code: response + .error + .code + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: response + .error + .message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: None, + }) + } +} + impl api::PaymentToken for Stripe {} impl diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index cc0010a43f4..6d203610ac8 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -94,6 +94,8 @@ pub struct PaymentIntentRequest { pub return_url: String, pub confirm: bool, pub mandate: Option<String>, + pub payment_method: Option<String>, + pub customer: Option<String>, #[serde(flatten)] pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, @@ -104,6 +106,8 @@ pub struct PaymentIntentRequest { #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, + pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated + pub setup_future_usage: Option<enums::FutureUsage>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -116,10 +120,12 @@ pub struct SetupIntentRequest { pub metadata_txn_uuid: String, pub confirm: bool, pub usage: Option<enums::FutureUsage>, + pub customer: Option<String>, pub off_session: Option<bool>, pub return_url: Option<String>, #[serde(flatten)] pub payment_data: StripePaymentMethodData, + pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -159,6 +165,23 @@ pub struct StripeTokenResponse { pub object: String, } +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct CustomerRequest { + pub description: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub phone: Option<Secret<String>>, + pub name: Option<String>, +} + +#[derive(Debug, Eq, PartialEq, Deserialize)] +pub struct StripeCustomerResponse { + pub id: String, + pub description: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub phone: Option<Secret<String>>, + pub name: Option<String>, +} + #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankName { @@ -824,15 +847,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { }, None => StripeShippingAddress::default(), }; + let mut payment_method_options = None; - let (mut payment_data, mandate, billing_address) = { + let (mut payment_data, payment_method, billing_address) = { match item .request .mandate_id .clone() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id) + .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { - None => { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_id)) => { + (None, Some(mandate_id), StripeBillingAddress::default()) + } + Some(api_models::payments::MandateReferenceId::NetworkMandateId( + network_transaction_id, + )) => { + payment_method_options = Some(StripePaymentMethodOptions::Card { + mandate_options: None, + network_transaction_id: None, + mit_exemption: Some(MitExemption { + network_transaction_id, + }), + }); + (None, None, StripeBillingAddress::default()) + } + _ => { let (payment_method_data, payment_method_type, billing_address) = create_stripe_payment_method( item.request.payment_method_type.as_ref(), @@ -848,7 +887,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { (Some(payment_method_data), None, billing_address) } - Some(mandate_id) => (None, Some(mandate_id), StripeBillingAddress::default()), } }; @@ -902,8 +940,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, - mandate, + mandate: None, + payment_method_options, + payment_method, + customer: item.connector_customer.to_owned(), setup_mandate_details, + setup_future_usage: item.request.setup_future_usage, }) } } @@ -932,6 +974,8 @@ impl TryFrom<&types::VerifyRouterData> for SetupIntentRequest { return_url: item.return_url.clone(), off_session: item.request.off_session, usage: item.request.setup_future_usage, + payment_method_options: None, + customer: item.connector_customer.to_owned(), }) } } @@ -951,6 +995,18 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { } } +impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { + Ok(Self { + description: item.request.description.to_owned(), + email: item.request.email.to_owned(), + phone: item.request.phone.to_owned(), + name: item.request.name.to_owned(), + }) + } +} + #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeMetadata { pub order_id: String, @@ -1004,6 +1060,7 @@ pub struct PaymentIntentResponse { pub client_secret: Secret<String>, pub created: i32, pub customer: Option<String>, + pub payment_method: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, @@ -1011,6 +1068,7 @@ pub struct PaymentIntentResponse { pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub last_payment_error: Option<ErrorDetails>, + pub latest_attempt: Option<LatestAttempt>, //need a merchant to test this } #[derive(Debug, Default, Eq, PartialEq, Deserialize)] @@ -1100,11 +1158,13 @@ pub struct SetupIntentResponse { pub status: StripePaymentStatus, // Change to SetupStatus pub client_secret: Secret<String>, pub customer: Option<String>, + pub payment_method: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: StripeMetadata, pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, + pub latest_attempt: Option<LatestAttempt>, } impl<F, T> @@ -1119,15 +1179,19 @@ impl<F, T> services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) }); - let mandate_reference = - item.response + //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse + // Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call + let network_txn_id = item.response.latest_attempt.and_then(|latest_attempt| { + latest_attempt .payment_method_options .and_then(|payment_method_options| match payment_method_options { StripePaymentMethodOptions::Card { - mandate_options, .. - } => mandate_options.map(|mandate_options| mandate_options.reference), + network_transaction_id, + .. + } => network_transaction_id, _ => None, - }); + }) + }); Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -1138,8 +1202,9 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data, - mandate_reference, + mandate_reference: item.response.payment_method, connector_metadata: None, + network_txn_id, }), amount_captured: Some(item.response.amount_received), ..item.data @@ -1209,6 +1274,7 @@ impl<F, T> redirection_data, mandate_reference, connector_metadata: None, + network_txn_id: None, }), Err, ); @@ -1234,23 +1300,26 @@ impl<F, T> services::RedirectForm::from((next_action_response.get_url(), services::Method::Get)) }); - let mandate_reference = - item.response + let network_txn_id = item.response.latest_attempt.and_then(|latest_attempt| { + latest_attempt .payment_method_options .and_then(|payment_method_options| match payment_method_options { StripePaymentMethodOptions::Card { - mandate_options, .. - } => mandate_options.map(|mandate_option| mandate_option.reference), + network_transaction_id, + .. + } => network_transaction_id, _ => None, - }); + }) + }); Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data, - mandate_reference, + mandate_reference: item.response.payment_method, connector_metadata: None, + network_txn_id, }), ..item.data }) @@ -1481,12 +1550,14 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { } } -#[derive(Deserialize, Debug, Clone, Eq, PartialEq)] +#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[non_exhaustive] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, + network_transaction_id: Option<String>, + mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, Affirm {}, @@ -1504,9 +1575,19 @@ pub enum StripePaymentMethodOptions { #[serde(rename = "bacs_debit")] Bacs {}, } + +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct MitExemption { + pub network_transaction_id: String, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] +pub struct LatestAttempt { + pub payment_method_options: Option<StripePaymentMethodOptions>, +} // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card -#[derive(serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] +#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub struct StripeMandateOptions { reference: String, // Extendable, But only important field to be captured } @@ -1543,6 +1624,23 @@ impl<F, T> } } +impl<F, T> + TryFrom<types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id: item.response.id, + }), + ..item.data + }) + } +} + // #[cfg(test)] // mod test_stripe_transformers { // use super::*; diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index e0e639610e5..c3cbbc1090d 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -580,6 +580,7 @@ fn handle_cards_response( redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, error, payment_response_data)) } @@ -606,6 +607,7 @@ fn handle_bank_redirects_response( ))), mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, error, payment_response_data)) } @@ -636,6 +638,7 @@ fn handle_bank_redirects_error_response( redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, error, payment_response_data)) } @@ -676,6 +679,7 @@ fn handle_bank_redirects_sync_response( redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, error, payment_response_data)) } @@ -696,6 +700,7 @@ pub fn handle_webhook_response( redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }; Ok((status, None, payment_response_data)) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 1bd446a72c8..c2c05df8b7a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -62,6 +62,7 @@ pub trait RouterData { T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<String, Error>; + fn get_customer_id(&self) -> Result<String, Error>; } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { @@ -145,6 +146,11 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .clone() .ok_or_else(missing_field_err("payment_method_token")) } + fn get_customer_id(&self) -> Result<String, Error> { + self.customer_id + .to_owned() + .ok_or_else(missing_field_err("customer_id")) + } } pub trait PaymentsAuthorizeRequestData { @@ -196,14 +202,19 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id.clone()) + .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => Some(connector_mandate_id.to_string()), + _ => None, + }) } fn is_mandate_payment(&self) -> bool { self.setup_mandate_details.is_some() || self .mandate_id .as_ref() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id.as_ref()) + .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn get_webhook_url(&self) -> Result<String, Error> { diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 6b580815b1c..4b34d054315 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -352,6 +352,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsRespo redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) @@ -380,6 +381,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::Payme redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index d6257cae4ad..6839636d8a7 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -175,6 +175,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..data.clone() }) @@ -271,6 +272,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..data.clone() }) @@ -328,6 +330,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..data.clone() }) diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index a80af7574ac..bbb8cb35fff 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -158,6 +158,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index df077c3bbf7..c273743b24d 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -295,6 +295,7 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }), ..item.data }) diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 4462a1e3e8b..345245ab84f 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -69,6 +69,7 @@ pub async fn create_customer( description: customer_data.description, phone_country_code: customer_data.phone_country_code, metadata: customer_data.metadata, + connector_customer: None, }; let customer = match db.insert_customer(new_customer).await { @@ -205,6 +206,7 @@ pub async fn delete_customer( description: Some(REDACTED.to_string()), phone_country_code: Some(REDACTED.to_string()), metadata: None, + connector_customer: None, }; db.update_customer_by_customer_id_merchant_id( req.customer_id.clone(), @@ -282,6 +284,7 @@ pub async fn update_customer( phone_country_code: update_customer.phone_country_code, metadata: update_customer.metadata, description: update_customer.description, + connector_customer: None, }, ) .await diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index d88f3f0ae9c..25f7f3ab69a 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -149,12 +149,13 @@ where None => { if resp.request.get_setup_mandate_details().is_some() { resp.payment_method_id = pm_id.clone(); - let mandate_reference = match resp.response.as_ref().ok() { + let (mandate_reference, network_txn_id) = match resp.response.as_ref().ok() { Some(types::PaymentsResponseData::TransactionResponse { mandate_reference, + network_txn_id, .. - }) => mandate_reference.clone(), - _ => None, + }) => (mandate_reference.clone(), network_txn_id.clone()), + _ => (None, None), }; if let Some(new_mandate_data) = helpers::generate_mandate( @@ -164,13 +165,30 @@ where maybe_customer, pm_id.get_required_value("payment_method_id")?, mandate_reference, + network_txn_id, ) { let connector = new_mandate_data.connector.clone(); logger::debug!("{:?}", new_mandate_data); resp.request .set_mandate_id(api_models::payments::MandateIds { mandate_id: new_mandate_data.mandate_id.clone(), - connector_mandate_id: new_mandate_data.connector_mandate_id.clone(), + mandate_reference_id: new_mandate_data + .connector_mandate_id + .clone() + .map_or( + new_mandate_data.network_transaction_id.clone().map(|id| { + api_models::payments::MandateReferenceId::NetworkMandateId( + id, + ) + }), + |connector_id| { + Some( + api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_id, + ), + ) + }, + ), }); state .store diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f2a7fdc9b83..4bb67bdb559 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -104,10 +104,19 @@ where ) .await?; - let (payment_data, tokenization_action) = + let (mut payment_data, tokenization_action) = get_connector_tokenization_action(state, &operation, payment_data, &validate_result) .await?; + let updated_customer = call_create_connector_customer( + state, + &connector, + &customer, + &merchant_account, + &mut payment_data, + ) + .await?; + let (operation, mut payment_data) = operation .to_update_tracker()? .update_trackers( @@ -116,6 +125,7 @@ where payment_data, customer.clone(), validate_result.storage_scheme, + updated_customer, ) .await?; @@ -469,7 +479,7 @@ where let stime_connector = Instant::now(); let mut router_data = payment_data - .construct_router_data(state, connector.connector.id(), merchant_account) + .construct_router_data(state, connector.connector.id(), merchant_account, customer) .await?; let add_access_token_result = router_data @@ -539,7 +549,7 @@ where for connector in connectors.iter() { let connector_id = connector.connector.id(); let router_data = payment_data - .construct_router_data(state, connector_id, merchant_account) + .construct_router_data(state, connector_id, merchant_account, customer) .await?; let res = router_data.decide_flows( @@ -583,6 +593,50 @@ where Ok(payment_data) } +pub async fn call_create_connector_customer<F, Req>( + state: &AppState, + connector: &Option<api::ConnectorCallType>, + customer: &Option<storage::Customer>, + merchant_account: &storage::MerchantAccount, + payment_data: &mut PaymentData<F>, +) -> RouterResult<Option<storage::CustomerUpdate>> +where + F: Send + Clone + Sync, + Req: Send + Sync, + + // To create connector flow specific interface data + PaymentData<F>: ConstructFlowSpecificData<F, Req, types::PaymentsResponseData>, + types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req> + Send, + + // To construct connector flow specific api + dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>, + + // To perform router related operation for PaymentResponse + PaymentResponse: Operation<F, Req>, +{ + match connector { + Some(connector_details) => match connector_details { + api::ConnectorCallType::Single(connector) => { + let router_data = payment_data + .construct_router_data( + state, + connector.connector.id(), + merchant_account, + customer, + ) + .await?; + let (connector_customer, customer_update) = router_data + .create_connector_customer(state, connector, customer) + .await?; + payment_data.connector_customer_id = connector_customer; + Ok(customer_update) + } + api::ConnectorCallType::Multiple(_) => Ok(None), + }, + None => Ok(None), + } +} + fn is_payment_method_tokenization_enabled_for_connector( state: &AppState, connector_name: &str, @@ -766,6 +820,7 @@ where pub email: Option<masking::Secret<String, pii::Email>>, pub creds_identifier: Option<String>, pub pm_token: Option<String>, + pub connector_customer_id: Option<String>, } #[derive(Debug, Default)] diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 8f8a447494a..ea5f7ad3dc7 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -26,6 +26,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::RouterData<F, Req, Res>>; } @@ -68,6 +69,20 @@ pub trait Feature<F, T> { { Ok(None) } + + async fn create_connector_customer<'a>( + &self, + _state: &AppState, + _connector: &api::ConnectorData, + _customer: &Option<storage::Customer>, + ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> + where + F: Clone, + Self: Sized, + dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, + { + Ok((None, None)) + } } macro_rules! default_imp_for_complete_authorize{ @@ -111,6 +126,53 @@ default_imp_for_complete_authorize!( connector::Zen ); +macro_rules! default_imp_for_create_customer{ + ($($path:ident::$connector:ident),*)=> { + $( + impl api::ConnectorCustomer for $path::$connector {} + impl + services::ConnectorIntegration< + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_create_customer!( + connector::Aci, + connector::Adyen, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bambora, + connector::Bluesnap, + connector::Braintree, + connector::Checkout, + connector::Coinbase, + connector::Cybersource, + connector::Dlocal, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Nexinets, + connector::Nuvei, + connector::Opennode, + connector::Payeezy, + connector::Paypal, + connector::Payu, + connector::Rapyd, + connector::Shift4, + connector::Trustpay, + connector::Worldline, + connector::Worldpay, + connector::Zen +); + macro_rules! default_imp_for_connector_redirect_response{ ($($path:ident::$connector:ident),*)=> { $( diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index b5432f0fb20..8e5093205f8 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -34,6 +34,7 @@ impl state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult< types::RouterData< api::Authorize, @@ -46,6 +47,7 @@ impl self.clone(), connector_id, merchant_account, + customer, ) .await } @@ -93,6 +95,15 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu ) -> RouterResult<Option<String>> { add_payment_method_token(state, connector, tokenization_action, self).await } + + async fn create_connector_customer<'a>( + &self, + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, + ) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + create_connector_customer(state, connector, customer, self).await + } } impl types::PaymentsAuthorizeRouterData { @@ -367,6 +378,151 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { } } +pub async fn update_connector_customer_in_customers( + connector: &api::ConnectorData, + connector_customer_map: Option<serde_json::Map<String, serde_json::Value>>, + connector_cust_id: &Option<String>, +) -> RouterResult<Option<storage::CustomerUpdate>> { + let mut connector_customer = match connector_customer_map { + Some(cc) => cc, + None => serde_json::Map::new(), + }; + connector_cust_id.clone().map(|cc| { + connector_customer.insert( + connector.connector_name.to_string(), + serde_json::Value::String(cc), + ) + }); + Ok(Some(storage::CustomerUpdate::ConnectorCustomer { + connector_customer: Some(serde_json::Value::Object(connector_customer)), + })) +} + +type CreateCustomerCheck = ( + bool, + Option<String>, + Option<serde_json::Map<String, serde_json::Value>>, +); +pub fn should_call_connector_create_customer( + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, +) -> RouterResult<CreateCustomerCheck> { + let connector_name = connector.connector_name.to_string(); + //Check if create customer is required for the connector + let connector_customer_filter = state + .conf + .connector_customer + .connector_list + .contains(&connector.connector_name); + if connector_customer_filter { + match customer { + Some(customer) => match &customer.connector_customer { + Some(connector_customer) => { + let connector_customer_map: serde_json::Map<String, serde_json::Value> = + connector_customer + .clone() + .parse_value("Map<String, Value>") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Value to CustomerConnector")?; + let value = connector_customer_map.get(&connector_name); //Check if customer already created for this customer and for this connector + Ok(( + value.is_none(), + value.and_then(|val| val.as_str().map(|cust| cust.to_string())), + Some(connector_customer_map), + )) + } + None => Ok((true, None, None)), + }, + None => Ok((false, None, None)), + } + } else { + Ok((false, None, None)) + } +} + +pub async fn create_connector_customer<F: Clone>( + state: &AppState, + connector: &api::ConnectorData, + customer: &Option<storage::Customer>, + router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, +) -> RouterResult<(Option<String>, Option<storage::CustomerUpdate>)> { + let (is_eligible, connector_customer_id, connector_customer_map) = + should_call_connector_create_customer(state, connector, customer)?; + + if is_eligible { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = + Err(types::ErrorResponse::default()); + + let customer_request_data = + types::ConnectorCustomerData::try_from(router_data.request.to_owned())?; + + let customer_router_data = payments::helpers::router_data_type_conversion::< + _, + api::CreateConnectorCustomer, + _, + _, + _, + _, + >( + router_data.clone(), + customer_request_data, + customer_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &customer_router_data, + payments::CallConnectorAction::Trigger, + ) + .await + .map_err(|error| error.to_payment_failed_response())?; + + let connector_customer_id = match resp.response { + Ok(response) => match response { + types::PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id, + } => Some(connector_customer_id), + _ => None, + }, + Err(err) => { + logger::debug!(payment_method_tokenization_error=?err); + None + } + }; + let update_customer = update_connector_customer_in_customers( + connector, + connector_customer_map, + &connector_customer_id, + ) + .await?; + Ok((connector_customer_id, update_customer)) + } else { + Ok((connector_customer_id, None)) + } +} + +impl TryFrom<types::PaymentsAuthorizeData> for types::ConnectorCustomerData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(data: types::PaymentsAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + email: data.email, + description: None, + phone: None, + name: None, + }) + } +} + pub async fn add_payment_method_token<F: Clone>( state: &AppState, connector: &api::ConnectorData, diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 276cc6b9bdc..0f5e5ca2814 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -20,12 +20,14 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::PaymentsCancelRouterData> { transformers::construct_payment_router_data::<api::Void, types::PaymentsCancelData>( state, self.clone(), connector_id, merchant_account, + customer, ) .await } diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index e192dc7fc68..7a4d9d53c27 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -21,12 +21,14 @@ impl state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::PaymentsCaptureRouterData> { transformers::construct_payment_router_data::<api::Capture, types::PaymentsCaptureData>( state, self.clone(), connector_id, merchant_account, + customer, ) .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 0e5f360703b..b8712d52f6d 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -24,6 +24,7 @@ impl state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult< types::RouterData< api::CompleteAuthorize, @@ -34,7 +35,13 @@ impl transformers::construct_payment_router_data::< api::CompleteAuthorize, types::CompleteAuthorizeData, - >(state, self.clone(), connector_id, merchant_account) + >( + state, + self.clone(), + connector_id, + merchant_account, + customer, + ) .await } } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 61127956c0a..f4cfcc1e001 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -20,6 +20,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { @@ -28,6 +29,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme self.clone(), connector_id, merchant_account, + customer, ) .await } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 53abde90bd0..e95f0c5af4a 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -27,12 +27,14 @@ impl state: &routes::AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::PaymentsSessionRouterData> { transformers::construct_payment_router_data::<api::Session, types::PaymentsSessionData>( state, self.clone(), connector_id, merchant_account, + customer, ) .await } diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 0f97ad77d91..2a6f38f144b 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -21,12 +21,14 @@ impl ConstructFlowSpecificData<api::Verify, types::VerifyRequestData, types::Pay state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::VerifyRouterData> { transformers::construct_payment_router_data::<api::Verify, types::VerifyRequestData>( state, self.clone(), connector_id, merchant_account, + customer, ) .await } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 40e17d1a01d..37a414d38cd 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1137,6 +1137,7 @@ pub fn generate_mandate( customer: &Option<storage::Customer>, payment_method_id: String, connector_mandate_id: Option<String>, + network_txn_id: Option<String>, ) -> Option<storage::MandateNew> { match (setup_mandate_details, customer) { (Some(data), Some(cus)) => { @@ -1153,6 +1154,7 @@ pub fn generate_mandate( .set_connector(connector) .set_mandate_status(storage_enums::MandateStatus::Active) .set_connector_mandate_id(connector_mandate_id) + .set_network_transaction_id(network_txn_id) .set_customer_ip_address( data.customer_acceptance .get_ip_address() @@ -1489,5 +1491,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( session_token: router_data.session_token, reference_id: None, payment_method_token: router_data.payment_method_token, + customer_id: router_data.customer_id, + connector_customer: router_data.connector_customer, } } diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index daf1f1a9f1b..b53e3307fb8 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -139,6 +139,7 @@ pub trait UpdateTracker<F, D, Req>: Send { payment_data: D, customer: Option<storage::Customer>, storage_scheme: enums::MerchantStorageScheme, + updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, Req>, D)> where F: 'b + Send; diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 57c90ab3635..f589b61745d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> card_cvc: None, creds_identifier, pm_token: None, + connector_customer_id: None, }, None, )), @@ -162,6 +163,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for mut payment_data: PaymentData<F>, _customer: Option<Customer>, storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsCancelRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 968971f41a4..814839ef2e9 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -155,6 +155,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu card_cvc: None, creds_identifier, pm_token: None, + connector_customer_id: None, }, None, )) @@ -173,6 +174,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe payment_data: payments::PaymentData<F>, _customer: Option<storage::Customer>, _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsCaptureRequest>, payments::PaymentData<F>, 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 1e382179ecb..7d480e29bc2 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -197,6 +197,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co card_cvc: request.card_cvc.clone(), creds_identifier: None, pm_token: None, + connector_customer_id: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), @@ -286,6 +287,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple payment_data: PaymentData<F>, _customer: Option<storage::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> where F: 'b + Send, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 480eef30d2d..7d711b3e619 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -216,6 +216,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, + connector_customer_id: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), @@ -305,6 +306,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen mut payment_data: PaymentData<F>, customer: Option<storage::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, + updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> where F: 'b + Send, @@ -365,7 +367,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent.billing_address_id.clone(), ); - let customer_id = customer.map(|c| c.customer_id); + let customer_id = customer.clone().map(|c| c.customer_id); let return_url = payment_data.payment_intent.return_url.clone(); let setup_future_usage = payment_data.payment_intent.setup_future_usage; let business_label = Some(payment_data.payment_intent.business_label.clone()); @@ -391,6 +393,17 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + if let Some((updated_customer, customer)) = updated_customer.zip(customer) { + db.update_customer_by_customer_id_merchant_id( + customer.customer_id.to_owned(), + customer.merchant_id.to_owned(), + updated_customer, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update CustomerConnector in customer")?; + }; + Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 88ba6ffcab4..f3f9236a9d4 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -152,7 +152,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .change_context(errors::ApiErrorResponse::MandateNotFound); Some(mandate.map(|mandate_obj| api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, - connector_mandate_id: mandate_obj.connector_mandate_id, + mandate_reference_id: { + match ( + mandate_obj.network_transaction_id, + mandate_obj.connector_mandate_id, + ) { + (Some(network_tx_id), _) => { + Some(api_models::payments::MandateReferenceId::NetworkMandateId( + network_tx_id, + )) + } + (_, Some(connector_mandate_id)) => Some( + api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + ), + ), + (_, _) => None, + } + }, })) }) .await @@ -207,6 +224,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, + connector_customer_id: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), @@ -287,6 +305,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen mut payment_data: PaymentData<F>, _customer: Option<storage::Customer>, storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> where F: 'b + Send, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index b0bd32efae2..b4d092db305 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -176,6 +176,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym card_cvc: None, creds_identifier, pm_token: None, + connector_customer_id: None, }, Some(payments::CustomerDetails { customer_id: request.customer_id.clone(), @@ -198,6 +199,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM mut payment_data: PaymentData<F>, _customer: Option<storage::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::VerifyRequest>, PaymentData<F>)> where F: 'b + Send, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index a4849b5dc81..6af82659fe7 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -387,6 +387,7 @@ async fn payment_response_update_tracker<F: Clone, T>( types::PaymentsResponseData::SessionResponse { .. } => (None, None), types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), + types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None), types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), }, }; diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 27b819ca1f8..2a901eb6045 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -175,6 +175,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> card_cvc: None, creds_identifier, pm_token: None, + connector_customer_id: None, }, Some(customer_details), )) @@ -191,6 +192,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for mut payment_data: PaymentData<F>, _customer: Option<storage::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsSessionRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index f9723eff9ea..c5892806876 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -142,6 +142,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f card_cvc: None, creds_identifier: None, pm_token: None, + connector_customer_id: None, }, Some(customer_details), )) @@ -158,6 +159,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P payment_data: PaymentData<F>, _customer: Option<storage::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsStartRequest>, 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 3a347ea6868..ec25f5995e6 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -116,6 +116,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data: PaymentData<F>, _customer: Option<storage::Customer>, _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> where F: 'b + Send, @@ -133,6 +134,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo payment_data: PaymentData<F>, _customer: Option<storage::Customer>, _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, @@ -272,6 +274,7 @@ async fn get_tracker_for_sync< card_cvc: None, creds_identifier, pm_token: None, + connector_customer_id: None, }, None, )) diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 5e22592bc00..e84d5076b96 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -193,7 +193,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .change_context(errors::ApiErrorResponse::MandateNotFound); Some(mandate.map(|mandate_obj| api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, - connector_mandate_id: mandate_obj.connector_mandate_id, + mandate_reference_id: { + match ( + mandate_obj.network_transaction_id, + mandate_obj.connector_mandate_id, + ) { + (Some(network_tx_id), _) => { + Some(api_models::payments::MandateReferenceId::NetworkMandateId( + network_tx_id, + )) + } + (_, Some(connector_mandate_id)) => Some( + api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + ), + ), + (_, _) => None, + } + }, })) }) .await @@ -268,6 +285,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, + connector_customer_id: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), @@ -348,6 +366,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen mut payment_data: PaymentData<F>, customer: Option<storage::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> where F: 'b + Send, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e629cbf2c33..ba8dcfd4748 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -27,6 +27,7 @@ pub async fn construct_payment_router_data<'a, F, T>( payment_data: PaymentData<F>, connector_id: &str, merchant_account: &storage::MerchantAccount, + customer: &Option<storage::Customer>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -74,6 +75,7 @@ where redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None, }); let additional_data = PaymentAdditionalData { @@ -83,9 +85,12 @@ where state, }; + let customer_id = customer.to_owned().map(|customer| customer.customer_id); + router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.merchant_id.clone(), + customer_id, connector: connector_id.to_owned(), payment_id: payment_data.payment_attempt.payment_id.clone(), attempt_id: payment_data.payment_attempt.attempt_id.clone(), @@ -108,6 +113,7 @@ where session_token: None, reference_id: None, payment_method_token: payment_data.pm_token, + connector_customer: payment_data.connector_customer_id, }; Ok(router_data) diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index f2f06f07e67..bed8baa7726 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -63,6 +63,7 @@ pub async fn construct_refund_router_data<'a, F>( let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.merchant_id.clone(), + customer_id: payment_intent.customer_id.to_owned(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), @@ -96,6 +97,7 @@ pub async fn construct_refund_router_data<'a, F>( session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, }; Ok(router_data) @@ -279,6 +281,8 @@ pub async fn construct_accept_dispute_router_data<'a>( session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, + customer_id: None, }; Ok(router_data) } @@ -336,6 +340,8 @@ pub async fn construct_submit_evidence_router_data<'a>( session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, + customer_id: None, }; Ok(router_data) } @@ -398,6 +404,8 @@ pub async fn construct_upload_file_router_data<'a>( session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, + customer_id: None, }; Ok(router_data) } @@ -457,6 +465,8 @@ pub async fn construct_defend_dispute_router_data<'a>( session_token: None, reference_id: None, payment_method_token: None, + customer_id: None, + connector_customer: None, }; Ok(router_data) } diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index cbdd99e2fd5..7e1519b6faa 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -184,6 +184,7 @@ impl CustomerInterface for MockDb { description: customer_data.description, created_at: common_utils::date_time::now(), metadata: customer_data.metadata, + connector_customer: customer_data.connector_customer, modified_at: common_utils::date_time::now(), }; customers.push(customer.clone()); diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 6ca53865e0d..a799c9245b6 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -39,6 +39,8 @@ pub type RefundExecuteRouterData = RouterData<api::Execute, RefundsData, Refunds pub type RefundSyncRouterData = RouterData<api::RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData<api::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>; +pub type ConnectorCustomerRouterData = + RouterData<api::CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type RefreshTokenRouterData = RouterData<api::AccessTokenAuth, AccessTokenRequestData, AccessToken>; @@ -61,6 +63,12 @@ pub type TokenizationResponseRouterData<R> = ResponseRouterData< PaymentMethodTokenizationData, PaymentsResponseData, >; +pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData< + api::CreateConnectorCustomer, + R, + ConnectorCustomerData, + PaymentsResponseData, +>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; @@ -97,6 +105,12 @@ pub type TokenizationType = dyn services::ConnectorIntegration< PaymentsResponseData, >; +pub type ConnectorCustomerType = dyn services::ConnectorIntegration< + api::CreateConnectorCustomer, + ConnectorCustomerData, + PaymentsResponseData, +>; + pub type RefundExecuteType = dyn services::ConnectorIntegration<api::Execute, RefundsData, RefundsResponseData>; pub type RefundSyncType = @@ -143,6 +157,8 @@ pub type DefendDisputeRouterData = pub struct RouterData<Flow, Request, Response> { pub flow: PhantomData<Flow>, pub merchant_id: String, + pub customer_id: Option<String>, + pub connector_customer: Option<String>, pub connector: String, pub payment_id: String, pub attempt_id: String, @@ -214,6 +230,14 @@ pub struct AuthorizeSessionTokenData { pub amount: i64, } +#[derive(Debug, Clone)] +pub struct ConnectorCustomerData { + pub description: Option<String>, + pub email: Option<masking::Secret<String, Email>>, + pub phone: Option<masking::Secret<String>>, + pub name: Option<String>, +} + #[derive(Debug, Clone)] pub struct PaymentMethodTokenizationData { pub payment_method_data: payments::PaymentMethodData, @@ -302,6 +326,7 @@ pub enum PaymentsResponseData { redirection_data: Option<services::RedirectForm>, mandate_reference: Option<String>, connector_metadata: Option<serde_json::Value>, + network_txn_id: Option<String>, }, SessionResponse { session_token: api::SessionToken, @@ -317,6 +342,11 @@ pub enum PaymentsResponseData { TokenizationResponse { token: String, }, + + ConnectorCustomerResponse { + connector_customer_id: String, + }, + ThreeDSEnrollmentResponse { enrolled_v2: bool, related_transaction_id: Option<String>, @@ -628,7 +658,9 @@ impl<F1, F2, T1, T2> From<(&&mut RouterData<F1, T1, PaymentsResponseData>, T2)> payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), + customer_id: data.customer_id.clone(), payment_method_token: None, + connector_customer: data.connector_customer.clone(), } } } diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e33269b8aef..4c02ab9a758 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -83,6 +83,9 @@ pub struct Session; #[derive(Debug, Clone)] pub struct PaymentMethodToken; +#[derive(Debug, Clone)] +pub struct CreateConnectorCustomer; + #[derive(Debug, Clone)] pub struct Verify; @@ -169,6 +172,15 @@ pub trait PaymentToken: { } +pub trait ConnectorCustomer: + api::ConnectorIntegration< + CreateConnectorCustomer, + types::ConnectorCustomerData, + types::PaymentsResponseData, +> +{ +} + pub trait Payment: api_types::ConnectorCommon + PaymentAuthorize @@ -179,6 +191,7 @@ pub trait Payment: + PreVerify + PaymentSession + PaymentToken + + ConnectorCustomer { } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 4a944c2b7cc..52169d90726 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -21,6 +21,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { types::RouterData { flow: PhantomData, merchant_id: String::from("aci"), + customer_id: Some(String::from("aci")), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -71,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, } } @@ -82,6 +84,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { types::RouterData { flow: PhantomData, merchant_id: String::from("aci"), + customer_id: Some(String::from("aci")), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -111,6 +114,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, } } diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index eec99afd2ac..aa5c236db4c 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -21,6 +21,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { types::RouterData { flow: PhantomData, merchant_id: String::from("authorizedotnet"), + customer_id: Some(String::from("authorizedotnet")), connector: "authorizedotnet".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -71,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, } } @@ -83,6 +85,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { flow: PhantomData, connector_meta_data: None, merchant_id: String::from("authorizedotnet"), + customer_id: Some(String::from("authorizedotnet")), connector: "authorizedotnet".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -110,6 +113,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index d7019ba4096..c5815819e9f 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -364,6 +364,7 @@ pub trait ConnectorActions: Connector { RouterData { flow: PhantomData, merchant_id: self.get_name(), + customer_id: Some(self.get_name()), connector: self.get_name(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -394,6 +395,7 @@ pub trait ConnectorActions: Connector { session_token: None, reference_id: None, payment_method_token: None, + connector_customer: None, } } @@ -409,6 +411,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } @@ -592,6 +595,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, + Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Err(_) => None, } @@ -606,6 +610,7 @@ pub fn get_connector_metadata( redirection_data: _, mandate_reference: _, connector_metadata, + network_txn_id: _, }) => connector_metadata, _ => None, } diff --git a/crates/storage_models/src/customers.rs b/crates/storage_models/src/customers.rs index 180ecf022e4..6f9bb379ba8 100644 --- a/crates/storage_models/src/customers.rs +++ b/crates/storage_models/src/customers.rs @@ -16,6 +16,7 @@ pub struct CustomerNew { pub description: Option<String>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, + pub connector_customer: Option<serde_json::Value>, } #[derive(Clone, Debug, Identifiable, Queryable)] @@ -31,6 +32,7 @@ pub struct Customer { pub description: Option<String>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, + pub connector_customer: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, } @@ -43,6 +45,10 @@ pub enum CustomerUpdate { description: Option<String>, phone_country_code: Option<String>, metadata: Option<pii::SecretSerdeValue>, + connector_customer: Option<serde_json::Value>, + }, + ConnectorCustomer { + connector_customer: Option<serde_json::Value>, }, } @@ -55,6 +61,7 @@ pub struct CustomerUpdateInternal { description: Option<String>, phone_country_code: Option<String>, metadata: Option<pii::SecretSerdeValue>, + connector_customer: Option<serde_json::Value>, modified_at: Option<PrimitiveDateTime>, } @@ -68,6 +75,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { description, phone_country_code, metadata, + connector_customer, } => Self { name, email, @@ -75,7 +83,13 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { description, phone_country_code, metadata, + connector_customer, + modified_at: Some(common_utils::date_time::now()), + }, + CustomerUpdate::ConnectorCustomer { connector_customer } => Self { + connector_customer, modified_at: Some(common_utils::date_time::now()), + ..Default::default() }, } } diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index d6723fba9fb..9509216170e 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -106,6 +106,7 @@ diesel::table! { description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, + connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, } } diff --git a/migrations/2023-04-19-120503_update_customer_connector_customer/down.sql b/migrations/2023-04-19-120503_update_customer_connector_customer/down.sql new file mode 100644 index 00000000000..cfc9dcd340e --- /dev/null +++ b/migrations/2023-04-19-120503_update_customer_connector_customer/down.sql @@ -0,0 +1 @@ +ALTER TABLE customers DROP COLUMN connector_customer; \ No newline at end of file diff --git a/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql b/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql new file mode 100644 index 00000000000..cab5c6a076a --- /dev/null +++ b/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE customers +ADD COLUMN connector_customer JSONB; \ No newline at end of file
feat
PG Agnostic mandate using network_txns_id (Adyen, Authorizedotnet, Stripe) (#855)
fc581e08ff7bcd462f2ca2fbbfeb454a2aec549c
2024-08-09 05:47:53
github-actions
chore(version): 2024.08.09.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index acc0fa09d60..071b214e797 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.08.09.0 + +### Features + +- **core:** [Payment Link] add dynamic merchant fields ([#5512](https://github.com/juspay/hyperswitch/pull/5512)) ([`03f0ea1`](https://github.com/juspay/hyperswitch/commit/03f0ea1582c76f1ed9dc4ff2215e80d659e5591a)) +- Payment processor token for recurring payments ([#5508](https://github.com/juspay/hyperswitch/pull/5508)) ([`0cbbc92`](https://github.com/juspay/hyperswitch/commit/0cbbc92a4319cb51864f443462545ab6e1ec75b6)) + +### Refactors + +- Use business profile domain models instead of diesel models ([#5566](https://github.com/juspay/hyperswitch/pull/5566)) ([`e56ad0d`](https://github.com/juspay/hyperswitch/commit/e56ad0d6884c6505d73df048e73d6210db3aae46)) + +**Full Changelog:** [`2024.08.08.0...2024.08.09.0`](https://github.com/juspay/hyperswitch/compare/2024.08.08.0...2024.08.09.0) + +- - - + ## 2024.08.08.0 ### Bug Fixes
chore
2024.08.09.0
b3fefeb2aa3ab44cc889b0a782eadc07d84a5e89
2022-12-13 13:03:25
Sahebjot singh
feat(connector): integrate payments void, sync and refund flows for Braintree (#73)
false
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 24bf1ef15a0..dc4eaccc310 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -246,7 +246,7 @@ impl res: Bytes, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: braintree::ErrorResponse = res - .parse_struct("Error Response") + .parse_struct("Braintree Error Response") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(ErrorResponse { @@ -271,7 +271,7 @@ impl logger::debug!(payment_sync_response=?res); let response: braintree::BraintreePaymentsResponse = res .response - .parse_struct("braintree PaymentsResponse") + .parse_struct("Braintree PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, @@ -356,7 +356,7 @@ impl ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: braintree::BraintreePaymentsResponse = res .response - .parse_struct("Braintree Payments Response") + .parse_struct("Braintree PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; logger::debug!(braintreepayments_create_response=?response); types::ResponseRouterData { @@ -375,7 +375,7 @@ impl logger::debug!(braintreepayments_create_response=?res); let response: braintree::ErrorResponse = res - .parse_struct("ErrorResponse") + .parse_struct("Braintree ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), @@ -394,50 +394,94 @@ impl { fn get_headers( &self, - _req: &types::PaymentsCancelRouterData, + req: &types::PaymentsCancelRouterData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + let mut headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + (headers::X_ROUTER.to_string(), "test".to_string()), + (headers::X_API_VERSION.to_string(), "6".to_string()), + (headers::ACCEPT.to_string(), "application/json".to_string()), + ]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + headers.append(&mut api_key); + Ok(headers) } fn get_content_type(&self) -> &'static str { - "" + "application/json" } fn get_url( &self, - _req: &types::PaymentsCancelRouterData, - _connectors: Connectors, + req: &types::PaymentsCancelRouterData, + connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(format!( + "{}merchants/{}/transactions/{}/void", + self.base_url(connectors), + auth_type.merchant_account, + req.request.connector_transaction_id + )) } - fn get_request_body( - &self, - _req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) - } fn build_request( &self, - _req: &types::PaymentsCancelRouterData, - _connectors: Connectors, + req: &types::PaymentsCancelRouterData, + connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Put) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .headers(types::PaymentsVoidType::get_headers(self, req)?) + .body(types::PaymentsVoidType::get_request_body(self, req)?) + .build(), + )) } - fn handle_response( + fn get_error_response( &self, - _data: &types::PaymentsCancelRouterData, - _res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + res: Bytes, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: braintree::ErrorResponse = res + .parse_struct("Braintree ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: response.api_error_response.message, + reason: None, + }) } - fn get_error_response( + fn get_request_body( &self, - _res: Bytes, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + _req: &types::PaymentsCancelRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + Ok(None) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + logger::debug!(payment_sync_response=?res); + let response: braintree::BraintreePaymentsResponse = res + .response + .parse_struct("Braintree PaymentsVoidResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } } @@ -467,23 +511,32 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref } fn get_content_type(&self) -> &'static str { - "" + "application/json" } fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: Connectors, + req: &types::RefundsRouterData<api::Execute>, + connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into()) + let auth_type = BraintreeAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}merchants/{}/transactions/{}", + self.base_url(connectors), + auth_type.merchant_account, + connector_payment_id + )) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<String>, errors::ConnectorError> { - let braintree_req = utils::Encode::<braintree::RefundRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let braintree_req = + utils::Encode::<braintree::BraintreeRefundRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(braintree_req)) } @@ -509,7 +562,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref logger::debug!(target: "router::connector::braintree", response=?res); let response: braintree::RefundResponse = res .response - .parse_struct("braintree RefundResponse") + .parse_struct("Braintree RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; types::ResponseRouterData { response, @@ -584,7 +637,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun logger::debug!(target: "router::connector::braintree", response=?res); let response: braintree::RefundResponse = res .response - .parse_struct("braintree RefundResponse") + .parse_struct("Braintree RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::ResponseRouterData { response, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 6ab8aff0b3d..985942204b5 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -44,11 +44,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { api::PaymentMethod::Card(ref ccard) => { + let submit_for_settlement = matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ); let braintree_payment_request = TransactionBody { amount: item.request.amount.to_string(), device_data: DeviceData {}, options: PaymentOptions { - submit_for_settlement: true, + submit_for_settlement, }, credit_card: Card { number: ccard.card_number.peek().clone(), @@ -62,7 +66,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { transaction: braintree_payment_request, }) } - _ => Err(errors::ConnectorError::RequestEncodingFailed.into()), + _ => Err( + errors::ConnectorError::NotImplemented("Current Payment Method".to_string()).into(), + ), } } } @@ -140,6 +146,7 @@ impl<F, T> >, ) -> Result<Self, Self::Error> { Ok(types::RouterData { + status: enums::AttemptStatus::from(item.response.transaction.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction.id, @@ -223,12 +230,21 @@ pub struct ApiErrorResponse { } #[derive(Default, Debug, Clone, Serialize)] -pub struct RefundRequest {} +pub struct BraintreeRefundRequest { + transaction: Amount, +} -impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest { - type Error = error_stack::Report<errors::ParsingError>; +#[derive(Default, Debug, Serialize, Clone)] +pub struct Amount { + amount: Option<String>, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - Ok(RefundRequest {}) + Ok(BraintreeRefundRequest { + transaction: Amount { amount: None }, + }) } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 1ef2da29c32..c1f632e4043 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -229,6 +229,7 @@ async fn send_request( .await } + Method::Put => client.put(url).add_headers(headers).send().await, Method::Delete => client.delete(url).add_headers(headers).send().await, } .into_report() diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 8f455a87362..04cb0413c42 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -20,6 +20,7 @@ pub(crate) type Headers = Vec<(String, String)>; pub enum Method { Get, Post, + Put, Delete, } diff --git a/scripts/create_connector_account.sh b/scripts/create_connector_account.sh index b3a2eebab90..4815197ebac 100644 --- a/scripts/create_connector_account.sh +++ b/scripts/create_connector_account.sh @@ -39,6 +39,7 @@ case "$connector" in authorizedotnet) required_connector="authorizedotnet";; aci) required_connector="aci";; adyen) required_connector="adyen";; + braintree) required_connector="braintree";; *) echo "This connector is not supported" 1>&2;exit 1;; esac
feat
integrate payments void, sync and refund flows for Braintree (#73)
ba0b7161e89f83c310aab96880f2f6c2761f6619
2023-09-27 12:07:35
github-actions
chore(version): v1.47.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index eb54ed9a85f..d1f37059173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.47.0 (2023-09-27) + +### Features + +- **connector_response:** Kv for connector response table ([#2207](https://github.com/juspay/hyperswitch/pull/2207)) ([`cefa291`](https://github.com/juspay/hyperswitch/commit/cefa291c00c7d4a40213cc6c6087946c031ae0b5)) + +### Bug Fixes + +- **connector:** + - Make webhook source verification mandatory for adyen ([#2360](https://github.com/juspay/hyperswitch/pull/2360)) ([`3d7e22a`](https://github.com/juspay/hyperswitch/commit/3d7e22a4f106e4d7c4224fecf455e2f2aa417cd0)) + - [noon] Create psync struct from webhook resource object ([#2370](https://github.com/juspay/hyperswitch/pull/2370)) ([`f12a438`](https://github.com/juspay/hyperswitch/commit/f12a43817787faedfdca26ec7f956bf5734c5ee3)) +- **merchant_connector_account:** Use appropriate key when redacting ([#2363](https://github.com/juspay/hyperswitch/pull/2363)) ([`54645cd`](https://github.com/juspay/hyperswitch/commit/54645cdbf422d59b8751fa9dbb9a61cd72770b0a)) +- **router:** + - Fix refunds and payment_attempts kv flow ([#2362](https://github.com/juspay/hyperswitch/pull/2362)) ([`ef0df71`](https://github.com/juspay/hyperswitch/commit/ef0df7195d9a7c7cd384f6df9eb5a8b886914e2d)) + - Removed dynamic error messages ([#2168](https://github.com/juspay/hyperswitch/pull/2168)) ([`9c9d453`](https://github.com/juspay/hyperswitch/commit/9c9d45353596edb5dc5c19e1a6d8d42d05bae78c)) +- [stripe] Add customer balance in StripePaymentMethodDetailsResponse ([#2369](https://github.com/juspay/hyperswitch/pull/2369)) ([`67a3e8f`](https://github.com/juspay/hyperswitch/commit/67a3e8f534aa98a7331cb20a3877579efed6a348)) + +### Refactors + +- **connector:** + - [bluesnap]Enhance currency Mapping with ConnectorCurrencyCommon Trait ([#2193](https://github.com/juspay/hyperswitch/pull/2193)) ([`6db60b8`](https://github.com/juspay/hyperswitch/commit/6db60b8cd4319d0246c72494fa65082108ffd06e)) + - [Zen] Enhance currency Mapping with ConnectorCurrencyCommon Trait ([#2196](https://github.com/juspay/hyperswitch/pull/2196)) ([`7fd79e0`](https://github.com/juspay/hyperswitch/commit/7fd79e05d54e6f135fbd4151d6638060660e6c85)) + - [Paypal]Enhance currency Mapping with ConnectorCurrencyCommon Trait ([#2191](https://github.com/juspay/hyperswitch/pull/2191)) ([`2e97869`](https://github.com/juspay/hyperswitch/commit/2e97869fa0e284e1ab3bcaf940b627acf47d98e3)) + - [Cryptopay]Enhance currency Mapping with ConnectorCurrencyCommon Trait ([#2195](https://github.com/juspay/hyperswitch/pull/2195)) ([`d8c3845`](https://github.com/juspay/hyperswitch/commit/d8c384573e1f31ed4c8fd252b8d753a04a4df75d)) + +### Miscellaneous Tasks + +- **config:** [Multisafepay] Add configs for card mandates for Multisafepay ([#2372](https://github.com/juspay/hyperswitch/pull/2372)) ([`af3b9e9`](https://github.com/juspay/hyperswitch/commit/af3b9e90dbc733b436f84e47ebd62ef0b467c39c)) + +**Full Changelog:** [`v1.46.0...v1.47.0`](https://github.com/juspay/hyperswitch/compare/v1.46.0...v1.47.0) + +- - - + + ## 1.46.0 (2023-09-25) ### Features
chore
v1.47.0
d974e6e7c2e1e3cd99607183b647c420f4b14d20
2024-05-07 19:20:43
Swangi Kumari
feat(connector): [MiFinity] add connector template code (#4447)
false
diff --git a/config/config.example.toml b/config/config.example.toml index f0dad483c65..d43668c4466 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -194,6 +194,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" @@ -259,7 +260,8 @@ stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,ba # This data is used to call respective connectors for wallets and cards [connectors.supported] -wallets = ["klarna", "braintree", "applepay"] +wallets = ["klarna", + "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "adyen", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index faf3bb7f466..1c4dc0e7bf2 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -49,6 +49,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index f564b976bc0..e136c05342a 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -53,6 +53,7 @@ gocardless.base_url = "https://api.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://secure.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 35c8a2ba3d6..3468c443a1d 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -53,6 +53,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" diff --git a/config/development.toml b/config/development.toml index 3f05872bc6a..83730662adc 100644 --- a/config/development.toml +++ b/config/development.toml @@ -88,7 +88,8 @@ vault_private_key = "" tunnel_private_key = "" [connectors.supported] -wallets = ["klarna", "braintree", "applepay", "adyen"] +wallets = ["klarna", + "mifinity", "braintree", "applepay", "adyen"] rewards = ["cashtocode", "zen"] cards = [ "aci", @@ -193,6 +194,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9fd22f46707..7dfab5548bf 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -128,6 +128,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" @@ -172,7 +173,8 @@ zsl.base_url = "https://api.sitoffalb.net/" apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } [connectors.supported] -wallets = ["klarna", "braintree", "applepay"] +wallets = ["klarna", + "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "aci", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index aed9915366f..93e20dc2e2c 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -98,6 +98,7 @@ pub enum Connector { Helcim, Iatapay, Klarna, + // Mifinity, Added as template code for future usage Mollie, Multisafepay, Netcetera, @@ -210,6 +211,7 @@ impl Connector { | Self::Helcim | Self::Iatapay | Self::Klarna + // | Self::Mifinity Added as template code for future usage | Self::Mollie | Self::Multisafepay | Self::Nexinets diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3c86064731b..70dc1ade0a6 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -137,6 +137,7 @@ pub enum RoutableConnectors { Helcim, Iatapay, Klarna, + Mifinity, Mollie, Multisafepay, Nexinets, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 5b55ca8b0e3..a07fa9ad2b4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -515,6 +515,7 @@ pub struct Connectors { pub helcim: ConnectorParams, pub iatapay: ConnectorParams, pub klarna: ConnectorParams, + pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 01c22651cd0..3f61a554f86 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -26,6 +26,7 @@ pub mod gocardless; pub mod helcim; pub mod iatapay; pub mod klarna; +pub mod mifinity; pub mod mollie; pub mod multisafepay; pub mod netcetera; @@ -69,11 +70,11 @@ pub use self::{ checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, - mollie::Mollie, multisafepay::Multisafepay, netcetera::Netcetera, 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, - zsl::Zsl, + mifinity::Mifinity, mollie::Mollie, multisafepay::Multisafepay, netcetera::Netcetera, + 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, zsl::Zsl, }; diff --git a/crates/router/src/connector/mifinity.rs b/crates/router/src/connector/mifinity.rs new file mode 100644 index 00000000000..7183dd755e1 --- /dev/null +++ b/crates/router/src/connector/mifinity.rs @@ -0,0 +1,561 @@ +pub mod transformers; + +use std::fmt::Debug; + +use error_stack::{report, ResultExt}; +use masking::ExposeInterface; +use transformers as mifinity; + +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 Mifinity; + +impl api::Payment for Mifinity {} +impl api::PaymentSession for Mifinity {} +impl api::ConnectorAccessToken for Mifinity {} +impl api::MandateSetup for Mifinity {} +impl api::PaymentAuthorize for Mifinity {} +impl api::PaymentSync for Mifinity {} +impl api::PaymentCapture for Mifinity {} +impl api::PaymentVoid for Mifinity {} +impl api::Refund for Mifinity {} +impl api::RefundExecute for Mifinity {} +impl api::RefundSync for Mifinity {} +impl api::PaymentToken for Mifinity {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Mifinity +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Mifinity +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 Mifinity { + fn id(&self) -> &'static str { + "mifinity" + } + + 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.mifinity.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = mifinity::MifinityAuthType::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: mifinity::MifinityErrorResponse = res + .response + .parse_struct("MifinityErrorResponse") + .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 Mifinity { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Mifinity +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Mifinity +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Mifinity +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Mifinity +{ + 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 = mifinity::MifinityRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = mifinity::MifinityPaymentsRequest::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: mifinity::MifinityPaymentsResponse = res + .response + .parse_struct("Mifinity 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 Mifinity +{ + 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: mifinity::MifinityPaymentsResponse = res + .response + .parse_struct("mifinity 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 Mifinity +{ + 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: mifinity::MifinityPaymentsResponse = res + .response + .parse_struct("Mifinity 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 Mifinity +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Mifinity +{ + 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 = mifinity::MifinityRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = mifinity::MifinityRefundRequest::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: mifinity::RefundResponse = res + .response + .parse_struct("mifinity 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 Mifinity { + 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: mifinity::RefundResponse = res + .response + .parse_struct("mifinity 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 Mifinity { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs new file mode 100644 index 00000000000..e1c3d18d0be --- /dev/null +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -0,0 +1,244 @@ +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + types::{self, api, domain, storage::enums}, +}; + +//TODO: Fill the struct with respective fields +pub struct MifinityRouterData<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 MifinityRouterData<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 MifinityPaymentsRequest { + amount: i64, + card: MifinityCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct MifinityCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for MifinityPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &MifinityRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + domain::PaymentMethodData::Card(req_card) => { + let card = MifinityCard { + 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 MifinityAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for MifinityAuthType { + 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 MifinityPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<MifinityPaymentStatus> for enums::AttemptStatus { + fn from(item: MifinityPaymentStatus) -> Self { + match item { + MifinityPaymentStatus::Succeeded => Self::Charged, + MifinityPaymentStatus::Failed => Self::Failure, + MifinityPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct MifinityPaymentsResponse { + status: MifinityPaymentStatus, + id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, MifinityPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + MifinityPaymentsResponse, + 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 MifinityRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&MifinityRouterData<&types::RefundsRouterData<F>>> for MifinityRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &MifinityRouterData<&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 MifinityErrorResponse { + 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 ee06097a599..e0cfe0dee89 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1788,6 +1788,10 @@ pub(crate) fn validate_auth_and_metadata_type( use crate::connector::*; match connector_name { + // api_enums::Connector::Mifinity => { + // mifinity::transformers::MifinityAuthType::try_from(val)?; + // Ok(()) + // } Added as template code for future usage #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector1 | api_enums::Connector::DummyConnector2 diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 0687f5986ba..6980a362f75 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -160,6 +160,7 @@ default_imp_for_complete_authorize!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Multisafepay, connector::Netcetera, connector::Nexinets, @@ -238,6 +239,7 @@ default_imp_for_webhook_source_verification!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -324,6 +326,7 @@ default_imp_for_create_customer!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -405,6 +408,7 @@ default_imp_for_connector_redirect_response!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Multisafepay, connector::Netcetera, connector::Nexinets, @@ -468,6 +472,7 @@ default_imp_for_connector_request_id!( connector::Gocardless, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -556,6 +561,7 @@ default_imp_for_accept_dispute!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -665,6 +671,7 @@ default_imp_for_file_upload!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -751,6 +758,7 @@ default_imp_for_submit_evidence!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -837,6 +845,7 @@ default_imp_for_defend_dispute!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -921,6 +930,7 @@ default_imp_for_pre_processing_steps!( connector::Globepay, connector::Helcim, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -985,6 +995,7 @@ default_imp_for_payouts!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1069,6 +1080,7 @@ default_imp_for_payouts_create!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1156,6 +1168,7 @@ default_imp_for_payouts_eligibility!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1241,6 +1254,7 @@ default_imp_for_payouts_fulfill!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1325,6 +1339,7 @@ default_imp_for_payouts_cancel!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1411,6 +1426,7 @@ default_imp_for_payouts_quote!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1498,6 +1514,7 @@ default_imp_for_payouts_recipient!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1588,6 +1605,7 @@ default_imp_for_payouts_recipient_account!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1675,6 +1693,7 @@ default_imp_for_approve!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1763,6 +1782,7 @@ default_imp_for_reject!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1835,6 +1855,7 @@ default_imp_for_fraud_check!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -1923,6 +1944,7 @@ default_imp_for_frm_sale!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2011,6 +2033,7 @@ default_imp_for_frm_checkout!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2099,6 +2122,7 @@ default_imp_for_frm_transaction!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2187,6 +2211,7 @@ default_imp_for_frm_fulfillment!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2275,6 +2300,7 @@ default_imp_for_frm_record_return!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2360,6 +2386,7 @@ default_imp_for_incremental_authorization!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2445,6 +2472,7 @@ default_imp_for_revoking_mandates!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Netcetera, @@ -2572,6 +2600,7 @@ default_imp_for_connector_authentication!( connector::Helcim, connector::Iatapay, connector::Klarna, + connector::Mifinity, connector::Mollie, connector::Multisafepay, connector::Nexinets, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 57f51c7b8b0..4eb4538e77d 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -361,6 +361,7 @@ impl ConnectorData { enums::Connector::Helcim => Ok(Box::new(&connector::Helcim)), enums::Connector::Iatapay => Ok(Box::new(&connector::Iatapay)), enums::Connector::Klarna => Ok(Box::new(&connector::Klarna)), + // enums::Connector::Mifinity => Ok(Box::new(&connector::Mifinity)), Added as template code for future usage enums::Connector::Mollie => Ok(Box::new(&connector::Mollie)), enums::Connector::Nmi => Ok(Box::new(&connector::Nmi)), enums::Connector::Noon => Ok(Box::new(&connector::Noon)), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ce11251b83e..8b8ba753db3 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -231,6 +231,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Helcim => Self::Helcim, api_enums::Connector::Iatapay => Self::Iatapay, api_enums::Connector::Klarna => Self::Klarna, + // api_enums::Connector::Mifinity => Self::Mifinity, Added as template code for future usage api_enums::Connector::Mollie => Self::Mollie, api_enums::Connector::Multisafepay => Self::Multisafepay, api_enums::Connector::Netcetera => { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 78e67b7670a..2682c1fcf99 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -34,6 +34,7 @@ mod globepay; mod gocardless; mod helcim; mod iatapay; +mod mifinity; mod mollie; mod multisafepay; mod netcetera; diff --git a/crates/router/tests/connectors/mifinity.rs b/crates/router/tests/connectors/mifinity.rs new file mode 100644 index 00000000000..f0b58342684 --- /dev/null +++ b/crates/router/tests/connectors/mifinity.rs @@ -0,0 +1,421 @@ +use masking::Secret; +use router::types::{self, domain, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct MifinityTest; +impl ConnectorActions for MifinityTest {} +impl utils::Connector for MifinityTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Mifinity; + types::api::ConnectorData { + connector: Box::new(&Mifinity), + connector_name: types::Connector::Adyen, + // Added as Dummy connector as template code is added for future usage + 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() + .mifinity + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "mifinity".to_string() + } +} + +static CONNECTOR: MifinityTest = MifinityTest {}; + +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 scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::domain::PaymentMethodData::Card(domain::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::domain::PaymentMethodData::Card(domain::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::domain::PaymentMethodData::Card(domain::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 a1f7919cd78..b712eb2b384 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -218,3 +218,7 @@ api_key="API Key" [zsl] api_key= "Key" key1= "Merchant id" + + +[mifinity] +api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index b5c18cfa5d4..61ef75ee0fb 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -38,6 +38,7 @@ pub struct ConnectorAuthentication { pub gocardless: Option<HeaderKey>, pub helcim: Option<HeaderKey>, pub iatapay: Option<SignatureKey>, + pub mifinity: Option<HeaderKey>, pub mollie: Option<BodyKey>, pub multisafepay: Option<HeaderKey>, pub netcetera: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 799582c733f..892cf94005e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -95,6 +95,7 @@ gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" +mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" @@ -138,7 +139,8 @@ zsl.base_url = "https://api.sitoffalb.net/" apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } [connectors.supported] -wallets = ["klarna", "braintree", "applepay"] +wallets = ["klarna", + "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "aci", diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index ec7d820a139..201f6582dda 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -17306,6 +17306,7 @@ "helcim", "iatapay", "klarna", + "mifinity", "mollie", "multisafepay", "nexinets", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index d8e789408bb..9054712ba10 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 billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless helcim iatapay klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
feat
[MiFinity] add connector template code (#4447)
500405d78938772e0e9f8e3ce4f930d782c670fa
2023-10-13 19:14:55
Prasunna Soppa
feat(connector): [Paypal] use connector request reference id as reference for paypal (#2577)
false
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 1f872868a00..fd104ac4aa5 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -1091,7 +1091,7 @@ impl api::IncomingWebhook for Paypal { resource .purchase_units .first() - .map(|unit| unit.reference_id.clone()) + .and_then(|unit| unit.invoice_id.clone().or(unit.reference_id.clone())) .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), )) diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 78bd75efe14..72dccaed733 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -73,7 +73,9 @@ pub struct OrderAmount { #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct PurchaseUnitRequest { - reference_id: String, + reference_id: Option<String>, //reference for an item in purchase_units + invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions. amount: OrderAmount, } @@ -260,10 +262,13 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP currency_code: item.router_data.request.currency, value: item.amount.to_owned(), }; - let reference_id = item.router_data.attempt_id.clone(); + let connector_request_reference_id = + item.router_data.connector_request_reference_id.clone(); let purchase_units = vec![PurchaseUnitRequest { - reference_id, + reference_id: Some(connector_request_reference_id.clone()), + custom_id: Some(connector_request_reference_id.clone()), + invoice_id: Some(connector_request_reference_id), amount, }]; let card = item.router_data.request.get_card()?; @@ -304,9 +309,14 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP currency_code: item.router_data.request.currency, value: item.amount.to_owned(), }; - let reference_id = item.router_data.attempt_id.clone(); + + let connector_req_reference_id = + item.router_data.connector_request_reference_id.clone(); + let purchase_units = vec![PurchaseUnitRequest { - reference_id, + reference_id: Some(connector_req_reference_id.clone()), + custom_id: Some(connector_req_reference_id.clone()), + invoice_id: Some(connector_req_reference_id), amount, }]; let payment_source = @@ -367,9 +377,13 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP currency_code: item.router_data.request.currency, value: item.amount.to_owned(), }; - let reference_id = item.router_data.attempt_id.clone(); + let connector_req_reference_id = + item.router_data.connector_request_reference_id.clone(); + let purchase_units = vec![PurchaseUnitRequest { - reference_id, + reference_id: Some(connector_req_reference_id.clone()), + custom_id: Some(connector_req_reference_id.clone()), + invoice_id: Some(connector_req_reference_id), amount, }]; let payment_source = @@ -655,7 +669,8 @@ pub struct PaymentsCollection { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PurchaseUnitItem { - pub reference_id: String, + pub reference_id: Option<String>, + pub invoice_id: Option<String>, pub payments: PaymentsCollection, } @@ -680,11 +695,17 @@ pub struct PaypalLinks { rel: String, } +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RedirectPurchaseUnitItem { + pub invoice_id: String, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalRedirectResponse { id: String, intent: PaypalPaymentIntent, status: PaypalOrderStatus, + purchase_units: Vec<RedirectPurchaseUnitItem>, links: Vec<PaypalLinks>, } @@ -712,6 +733,7 @@ pub struct PaypalPaymentsSyncResponse { id: String, status: PaypalPaymentStatus, amount: OrderAmount, + invoice_id: Option<String>, supplementary_data: PaypalSupplementaryData, } @@ -792,7 +814,7 @@ impl<F, T> capture_id: Some(id), psync_flow: item.response.intent.clone() }), - types::ResponseId::ConnectorTransactionId(item.response.id), + types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), PaypalPaymentIntent::Authorize => ( @@ -801,7 +823,7 @@ impl<F, T> capture_id: None, psync_flow: item.response.intent.clone() }), - types::ResponseId::ConnectorTransactionId(item.response.id), + types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), PaypalPaymentIntent::Authenticate => { @@ -836,7 +858,10 @@ impl<F, T> mandate_reference: None, connector_metadata: Some(connector_meta), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: purchase_units + .invoice_id + .clone() + .or(Some(item.response.id)), }), ..item.data }) @@ -925,11 +950,12 @@ impl<F, T> capture_id: None, psync_flow: item.response.intent }); + let purchase_units = item.response.purchase_units.first(); Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Some(services::RedirectForm::from(( link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, services::Method::Get, @@ -937,7 +963,9 @@ impl<F, T> mandate_reference: None, connector_metadata: Some(connector_meta), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()), + ), }), ..item.data }) @@ -1075,13 +1103,21 @@ impl<F, T> status: storage_enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.supplementary_data.related_ids.order_id, + item.response + .supplementary_data + .related_ids + .order_id + .clone(), ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .invoice_id + .clone() + .or(Some(item.response.supplementary_data.related_ids.order_id)), }), ..item.data }) @@ -1133,6 +1169,7 @@ pub struct PaypalCaptureResponse { id: String, status: PaypalPaymentStatus, amount: Option<OrderAmount>, + invoice_id: Option<String>, final_capture: bool, } @@ -1174,11 +1211,14 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> mandate_reference: None, connector_metadata: Some(serde_json::json!(PaypalMeta { authorize_id: connector_payment_id.authorize_id, - capture_id: Some(item.response.id), + capture_id: Some(item.response.id.clone()), psync_flow: PaypalPaymentIntent::Capture })), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .invoice_id + .or(Some(item.response.id)), }), amount_captured: Some(amount_captured), ..item.data @@ -1193,11 +1233,11 @@ pub enum PaypalCancelStatus { } #[derive(Debug, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] pub struct PaypalPaymentsCancelResponse { id: String, status: PaypalCancelStatus, amount: Option<OrderAmount>, + invoice_id: Option<String>, } impl<F, T> @@ -1220,12 +1260,15 @@ impl<F, T> Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .invoice_id + .or(Some(item.response.id)), }), ..item.data }) @@ -1408,6 +1451,7 @@ pub struct PaypalSellerPayableBreakdown { pub struct PaypalCardWebhooks { pub supplementary_data: PaypalSupplementaryData, pub amount: OrderAmount, + pub invoice_id: Option<String>, } #[derive(Deserialize, Debug, Serialize)] @@ -1528,6 +1572,7 @@ impl TryFrom<(PaypalCardWebhooks, PaypalWebhookEventType)> for PaypalPaymentsSyn status: PaypalPaymentStatus::try_from(webhook_event)?, amount: webhook_body.amount, supplementary_data: webhook_body.supplementary_data, + invoice_id: webhook_body.invoice_id, }) } }
feat
[Paypal] use connector request reference id as reference for paypal (#2577)
1a8753485c52329f2be40dbaa9ba77c90e8262ed
2023-03-01 16:08:11
Arjun Karthik
fix(connector): fix wordline card number validation issue (#695)
false
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 4fadac89da3..511efe511bd 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -150,7 +150,10 @@ fn make_card_request( ); let expiry_date: Secret<String> = Secret::new(secret_value); let card = Card { - card_number: ccard.card_number.clone(), + card_number: ccard + .card_number + .clone() + .map(|card| card.split_whitespace().collect()), cardholder_name: ccard.card_holder_name.clone(), cvv: ccard.card_cvc.clone(), expiry_date, diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 4a10abe3091..d70faaa424d 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -91,7 +91,7 @@ impl WorldlineTest { #[actix_web::test] async fn should_requires_manual_authorization() { let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "5424 1802 7979 1732", "10", "25", "123", @@ -143,7 +143,7 @@ async fn should_throw_not_implemented_for_unsupported_issuer() { #[actix_web::test] async fn should_throw_missing_required_field_for_country() { let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "4012 0000 3333 0026", "10", "2025", "123", @@ -191,7 +191,7 @@ async fn should_fail_payment_for_invalid_cvc() { async fn should_sync_manual_auth_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "4012 0000 3333 0026", "10", "2025", "123", @@ -257,7 +257,7 @@ async fn should_sync_auto_auth_payment() { async fn should_capture_authorized_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "4012 0000 3333 0026", "10", "2025", "123", @@ -296,7 +296,7 @@ async fn should_fail_capture_payment() { async fn should_cancel_unauthorized_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "4012 0000 3333 0026", "10", "25", "123", @@ -356,7 +356,7 @@ async fn should_fail_cancel_with_invalid_payment_id() { async fn should_fail_refund_with_invalid_payment_status() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( - "4012000033330026", + "4012 0000 3333 0026", "10", "25", "123",
fix
fix wordline card number validation issue (#695)
863e380cf2eb8ace17cad0f1bcbc2a9f4a460983
2024-02-22 16:18:27
Narayan Bhat
feat(address): add email field to address (#3682)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b95b74b329f..91a289652b8 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1996,6 +1996,9 @@ pub struct Address { pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, + + #[schema(value_type = Option<String>)] + pub email: Option<Email>, } // used by customers also, could be moved outside diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index 03dedfd60d8..e3d5ed73992 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -25,6 +25,7 @@ pub struct AddressNew { pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub updated_by: String, + pub email: Option<Encryption>, } #[derive(Clone, Debug, Queryable, Identifiable, Serialize, Deserialize)] @@ -49,6 +50,7 @@ pub struct Address { pub merchant_id: String, pub payment_id: Option<String>, pub updated_by: String, + pub email: Option<Encryption>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] @@ -67,6 +69,7 @@ pub struct AddressUpdateInternal { pub country_code: Option<String>, pub modified_at: PrimitiveDateTime, pub updated_by: String, + pub email: Option<Encryption>, } impl AddressUpdateInternal { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 5093f0df7d0..be8c3302140 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -31,6 +31,7 @@ diesel::table! { payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, + email -> Nullable<Bytea>, } } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 9aa84db5fae..ba6bf286797 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -39,6 +39,7 @@ impl From<StripeBillingDetails> for payments::Address { address.country.as_ref().map(|country| country.to_string()) }), }), + email: details.email, address: details.address.map(|address| payments::AddressDetails { city: address.city, country: address.country, @@ -184,6 +185,7 @@ impl From<Shipping> for payments::Address { number: details.phone, country_code: details.address.country.map(|country| country.to_string()), }), + email: None, address: Some(payments::AddressDetails { city: details.address.city, country: details.address.country, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 5a2c7a02897..4dcea1c4fef 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -37,6 +37,7 @@ impl From<StripeBillingDetails> for payments::Address { number: details.phone, country_code: None, }), + email: details.email, } } } @@ -143,6 +144,7 @@ impl From<Shipping> for payments::Address { number: details.phone, country_code: None, }), + email: None, } } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 9442bf2ff34..5686cf4ec65 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -249,6 +249,12 @@ pub async fn delete_customer( .await .switch()?; + let redacted_encrypted_email: Encryptable< + masking::Secret<_, common_utils::pii::EmailStrategy>, + > = Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) + .await + .switch()?; + let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), country: None, @@ -262,6 +268,7 @@ pub async fn delete_customer( phone_number: Some(redacted_encrypted_value.clone()), country_code: Some(REDACTED.to_string()), updated_by: merchant_account.storage_scheme.to_string(), + email: Some(redacted_encrypted_email), }; match db 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 30918b2fe4e..3f43204b986 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -69,7 +69,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup .as_ref() .and_then(|mandate_data| mandate_data.update_mandate_id.clone()) { - self.update_mandate_flow( + Box::pin(self.update_mandate_flow( state, merchant_account, mandate_id, @@ -79,7 +79,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup &state.conf.mandates.update_mandate_supported, connector_request, maybe_customer, - ) + )) .await } else { let connector_integration: services::BoxedConnectorIntegration< diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b3330f82f74..b6e28faa4eb 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -181,6 +181,14 @@ pub async fn create_or_update_address_for_payment_by_request( .as_ref() .and_then(|value| value.country_code.clone()), updated_by: storage_scheme.to_string(), + email: address + .email + .as_ref() + .cloned() + .async_lift(|inner| { + types::encrypt_optional(inner.map(|inner| inner.expose()), key) + }) + .await?, }) } .await @@ -370,6 +378,12 @@ pub async fn get_domain_address_for_payments( .await?, payment_id: Some(payment_id.to_owned()), updated_by: storage_scheme.to_string(), + email: address + .email + .as_ref() + .cloned() + .async_lift(|inner| types::encrypt_optional(inner.map(|inner| inner.expose()), key)) + .await?, }) } .await diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 8741407d17b..ccb6f74c782 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -2,7 +2,7 @@ pub mod helpers; pub mod validator; use api_models::enums as api_enums; -use common_utils::{crypto::Encryptable, ext_traits::ValueExt}; +use common_utils::{crypto::Encryptable, ext_traits::ValueExt, pii}; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -1096,6 +1096,7 @@ pub async fn response_handler( api::payments::Address { phone: Some(phone_details), address: Some(address_details), + email: a.email.to_owned().map(pii::Email::from), } }); diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index ef8dddde955..21b10ecd1e7 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -108,6 +108,7 @@ pub async fn construct_payout_router_data<'a, F>( api_models::payments::Address { phone: Some(phone_details), address: Some(address_details), + email: a.email.to_owned().map(Email::from), } }), }; diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 99006752f57..311fdc127d1 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -501,6 +501,7 @@ mod storage { merchant_id: address_new.merchant_id.clone(), payment_id: address_new.payment_id.clone(), updated_by: storage_scheme.to_string(), + email: address_new.email.clone(), }; let redis_entry = kv::TypedSql { diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index ddf9c2152e9..c657aaf97ea 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -39,6 +39,7 @@ pub struct Address { pub merchant_id: String, pub payment_id: Option<String>, pub updated_by: String, + pub email: crypto::OptionalEncryptableEmail, } #[async_trait] @@ -67,6 +68,7 @@ impl behaviour::Conversion for Address { merchant_id: self.merchant_id, payment_id: self.payment_id, updated_by: self.updated_by, + email: self.email.map(Encryption::from), }) } @@ -76,6 +78,7 @@ impl behaviour::Conversion for Address { ) -> CustomResult<Self, ValidationError> { async { let inner_decrypt = |inner| types::decrypt(inner, key.peek()); + let inner_decrypt_email = |inner| types::decrypt(inner, key.peek()); Ok(Self { id: other.id, address_id: other.address_id, @@ -96,6 +99,7 @@ impl behaviour::Conversion for Address { merchant_id: other.merchant_id, payment_id: other.payment_id, updated_by: other.updated_by, + email: other.email.async_lift(inner_decrypt_email).await?, }) } .await @@ -125,6 +129,7 @@ impl behaviour::Conversion for Address { created_at: now, modified_at: now, updated_by: self.updated_by, + email: self.email.map(Encryption::from), }) } } @@ -144,6 +149,7 @@ pub enum AddressUpdate { phone_number: crypto::OptionalEncryptableSecretString, country_code: Option<String>, updated_by: String, + email: crypto::OptionalEncryptableEmail, }, } @@ -163,6 +169,7 @@ impl From<AddressUpdate> for AddressUpdateInternal { phone_number, country_code, updated_by, + email, } => Self { city, country, @@ -177,6 +184,7 @@ impl From<AddressUpdate> for AddressUpdateInternal { country_code, modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()), updated_by, + email: email.map(Encryption::from), }, } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index f9ba7f8e923..e0d608f3cd6 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -589,6 +589,7 @@ impl<'a> From<&'a domain::Address> for api_types::Address { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), }), + email: address.email.clone().map(pii::Email::from), } } } diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f9511a76d81..f218751204b 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -26,6 +26,7 @@ pub use common_utils::{ use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; use image::Luma; +use masking::ExposeInterface; use nanoid::nanoid; use qrcode; use serde::de::DeserializeOwned; @@ -564,6 +565,12 @@ impl CustomerAddress for api_models::customers::CustomerRequest { .await?, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), + email: self + .email + .as_ref() + .cloned() + .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) + .await?, }) } .await @@ -623,6 +630,12 @@ impl CustomerAddress for api_models::customers::CustomerRequest { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), + email: self + .email + .as_ref() + .cloned() + .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) + .await?, }) } .await diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 76e2a3052af..6f3a309b0fb 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -62,6 +62,7 @@ impl AdyenTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), @@ -88,6 +89,7 @@ impl AdyenTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 892d5b1f208..d24e20cd660 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -55,6 +55,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index 852b23f022c..622d835e838 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -54,6 +54,7 @@ fn get_payment_info() -> Option<PaymentInfo> { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 9d082445719..a9d81d2bb62 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -82,6 +82,7 @@ impl CashtocodeTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 9a476df7fe6..7a872ecb585 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -56,6 +56,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 5e1b3f5ab47..d61a93c8b82 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -55,6 +55,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 70255f68d89..617b1841560 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -54,6 +54,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs index 92ae9da11dc..6b3a2954b67 100644 --- a/crates/router/tests/connectors/dlocal.rs +++ b/crates/router/tests/connectors/dlocal.rs @@ -435,6 +435,7 @@ pub fn get_payment_info() -> PaymentInfo { first_name: None, last_name: None, }), + email: None, }), }), auth_type: None, diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs index fdc6647c86c..e017a11ff59 100644 --- a/crates/router/tests/connectors/forte.rs +++ b/crates/router/tests/connectors/forte.rs @@ -67,6 +67,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index 8553f2a768a..7cfd691c034 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -64,6 +64,7 @@ impl Globalpay { ..Default::default() }), phone: None, + ..Default::default() }), ..Default::default() }), diff --git a/crates/router/tests/connectors/iatapay.rs b/crates/router/tests/connectors/iatapay.rs index b6469b500c7..d138fe8518e 100644 --- a/crates/router/tests/connectors/iatapay.rs +++ b/crates/router/tests/connectors/iatapay.rs @@ -71,6 +71,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/multisafepay.rs b/crates/router/tests/connectors/multisafepay.rs index 8502a60b71c..ff56239e972 100644 --- a/crates/router/tests/connectors/multisafepay.rs +++ b/crates/router/tests/connectors/multisafepay.rs @@ -53,6 +53,7 @@ fn get_default_payment_info() -> Option<PaymentInfo> { state: Some(Secret::new("Amsterdam".to_string())), }), phone: None, + email: None, }), }); Some(PaymentInfo { diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 69edec2af2c..8415be949a0 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -55,6 +55,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+91".to_string()), }), + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs index 1176ad7322b..d05d065bcd9 100644 --- a/crates/router/tests/connectors/payeezy.rs +++ b/crates/router/tests/connectors/payeezy.rs @@ -62,6 +62,7 @@ impl PayeezyTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 206694be0e8..0ec07f4f724 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -57,6 +57,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { last_name: Some(Secret::new("Doe".to_string())), }), phone: None, + email: None, }), }), auth_type: None, diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index 6dcd78f58a7..560b7ba0b5e 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -80,6 +80,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs index de303523040..58fc74ed192 100644 --- a/crates/router/tests/connectors/wise.rs +++ b/crates/router/tests/connectors/wise.rs @@ -66,6 +66,7 @@ impl WiseTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 8b865789003..c5b12a0b0b2 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -50,6 +50,7 @@ impl WorldlineTest { ..Default::default() }), phone: None, + email: None, }), ..Default::default() }), diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 8f5ac25736c..8ab2779d97d 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -333,10 +333,12 @@ async fn payments_create_core() { shipping: Some(api::Address { address: None, phone: None, + email: None, }), billing: Some(api::Address { address: None, phone: None, + email: None, }), statement_descriptor_name: Some("Hyperswtich".to_string()), statement_descriptor_suffix: Some("Hyperswitch".to_string()), @@ -509,10 +511,12 @@ async fn payments_create_core_adyen_no_redirect() { shipping: Some(api::Address { address: None, phone: None, + email: None, }), billing: Some(api::Address { address: None, phone: None, + email: None, }), statement_descriptor_name: Some("Juspay".to_string()), statement_descriptor_suffix: Some("Router".to_string()), diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 89ac522d237..d901da342f3 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -93,10 +93,12 @@ async fn payments_create_core() { shipping: Some(api::Address { address: None, phone: None, + email: None, }), billing: Some(api::Address { address: None, phone: None, + email: None, }), statement_descriptor_name: Some("Hyperswitch".to_string()), statement_descriptor_suffix: Some("Hyperswitch".to_string()), @@ -273,9 +275,15 @@ async fn payments_create_core_adyen_no_redirect() { nick_name: Some(masking::Secret::new("nick_name".into())), })), payment_method: Some(api_enums::PaymentMethod::Card), + shipping: Some(api::Address { + address: None, + phone: None, + email: None, + }), billing: Some(api::Address { address: None, phone: None, + email: None, }), statement_descriptor_name: Some("Juspay".to_string()), statement_descriptor_suffix: Some("Router".to_string()), diff --git a/migrations/2024-02-15-133957_add_email_to_address/down.sql b/migrations/2024-02-15-133957_add_email_to_address/down.sql new file mode 100644 index 00000000000..8d3d6bd90a7 --- /dev/null +++ b/migrations/2024-02-15-133957_add_email_to_address/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE address DROP COLUMN IF EXISTS email; diff --git a/migrations/2024-02-15-133957_add_email_to_address/up.sql b/migrations/2024-02-15-133957_add_email_to_address/up.sql new file mode 100644 index 00000000000..5dce63c4b23 --- /dev/null +++ b/migrations/2024-02-15-133957_add_email_to_address/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE address +ADD COLUMN IF NOT EXISTS email BYTEA; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 9e64f3e9d03..27989e1eaee 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4315,6 +4315,10 @@ } ], "nullable": true + }, + "email": { + "type": "string", + "nullable": true } } }, 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 44aef3e03bb..3d51aaa49a8 100644 --- a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js +++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js @@ -19,7 +19,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) { @@ -88,3 +88,12 @@ pm.test( .true; }, ); + +// Response body should have "billing.email" +pm.test( + "[POST]::/payments - Content check if 'billing.email' exists", + function () { + pm.expect(typeof jsonData.connector_transaction_id !== "undefined").to.be + .true; + }, +); diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json b/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json index e149698461e..256d7a42097 100644 --- a/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json @@ -58,7 +58,8 @@ "phone": { "number": "8056594427", "country_code": "+91" - } + }, + "email": "[email protected]" }, "shipping": { "address": {
feat
add email field to address (#3682)
864a8d7b02acda5ea593cae83594962ea249c16d
2024-01-30 17:06:31
AkshayaFoiger
feat(connector): [Stripe] Metadata to connector metadata mapping (#3295)
false
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 70582c41aa4..8d397d0ebb9 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,4 +1,4 @@ -use std::ops::Deref; +use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_utils::{ @@ -9,11 +9,11 @@ use common_utils::{ }; use data_models::mandates::AcceptanceType; use error_stack::{IntoReport, ResultExt}; -use masking::{ExposeInterface, ExposeOptionInterface, Secret}; +use masking::{ExposeInterface, ExposeOptionInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; +use serde_json::Value; use time::PrimitiveDateTime; use url::Url; -use uuid::Uuid; use crate::{ collect_missing_value_keys, @@ -105,7 +105,7 @@ pub struct PaymentIntentRequest { pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, #[serde(flatten)] - pub meta_data: StripeMetadata, + pub meta_data: HashMap<String, String>, pub return_url: String, pub confirm: bool, pub mandate: Option<Secret<String>>, @@ -145,12 +145,6 @@ pub struct StripeMetadata { #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SetupIntentRequest { - #[serde(rename = "metadata[order_id]")] - pub metadata_order_id: String, - #[serde(rename = "metadata[txn_id]")] - pub metadata_txn_id: String, - #[serde(rename = "metadata[txn_uuid]")] - pub metadata_txn_uuid: String, pub confirm: bool, pub usage: Option<enums::FutureUsage>, pub customer: Option<Secret<String>>, @@ -159,6 +153,8 @@ pub struct SetupIntentRequest { #[serde(flatten)] pub payment_data: StripePaymentMethodData, pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated + #[serde(flatten)] + pub meta_data: Option<HashMap<String, String>>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -218,6 +214,8 @@ pub struct ChargesRequest { pub currency: String, pub customer: Secret<String>, pub source: Secret<String>, + #[serde(flatten)] + pub meta_data: Option<HashMap<String, String>>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] @@ -1877,15 +1875,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { None } }); + + let meta_data = get_transaction_metadata(item.request.metadata.clone(), order_id); + Ok(Self { amount: item.request.amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(), statement_descriptor: item.request.statement_descriptor.clone(), - meta_data: StripeMetadata { - order_id: Some(order_id), - is_refund_id_as_reference: None, - }, + meta_data, return_url: item .request .router_return_url @@ -1945,10 +1943,6 @@ fn get_payment_method_type_for_saved_payment_method_payment( impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { - let metadata_order_id = item.connector_request_reference_id.clone(); - let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); - let metadata_txn_uuid = Uuid::new_v4().to_string(); - //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from(( @@ -1957,17 +1951,20 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { pm_type, ))?; + let meta_data = Some(get_transaction_metadata( + item.request.metadata.clone(), + item.connector_request_reference_id.clone(), + )); + Ok(Self { confirm: true, - metadata_order_id, - metadata_txn_id, - metadata_txn_uuid, payment_data, return_url: item.request.router_return_url.clone(), off_session: item.request.off_session, usage: item.request.setup_future_usage, payment_method_options: None, customer: item.connector_customer.to_owned().map(Secret::new), + meta_data, }) } } @@ -2355,7 +2352,7 @@ impl<F, T> pub fn get_connector_metadata( next_action: Option<&StripeNextActionResponse>, amount: i64, -) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { +) -> CustomResult<Option<Value>, errors::ConnectorError> { let next_action_response = next_action .and_then(|next_action_response| match next_action_response { StripeNextActionResponse::DisplayBankTransferInstructions(response) => { @@ -3058,12 +3055,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for ChargesRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - Ok(Self { - amount: value.request.amount.to_string(), - currency: value.request.currency.to_string(), - customer: Secret::new(value.get_connector_customer_id()?), - source: Secret::new(value.get_preprocessing_id()?), - }) + { + let order_id = value.connector_request_reference_id.clone(); + let meta_data = Some(get_transaction_metadata( + value.request.metadata.clone(), + order_id, + )); + Ok(Self { + amount: value.request.amount.to_string(), + currency: value.request.currency.to_string(), + customer: Secret::new(value.get_connector_customer_id()?), + source: Secret::new(value.get_preprocessing_id()?), + meta_data, + }) + } } } @@ -3169,7 +3174,7 @@ impl<F, T> #[derive(Debug, Deserialize)] pub struct WebhookEventDataResource { - pub object: serde_json::Value, + pub object: Value, } #[derive(Debug, Deserialize)] @@ -3649,6 +3654,26 @@ pub struct DisputeObj { pub status: String, } +fn get_transaction_metadata( + merchant_metadata: Option<Secret<Value>>, + order_id: String, +) -> HashMap<String, String> { + let mut meta_data = HashMap::from([("metadata[order_id]".to_string(), order_id)]); + let mut request_hash_map = HashMap::new(); + + if let Some(metadata) = merchant_metadata { + let hashmap: HashMap<String, Value> = + serde_json::from_str(&metadata.peek().to_string()).unwrap_or(HashMap::new()); + + for (key, value) in hashmap { + request_hash_map.insert(format!("metadata[{}]", key), value.to_string()); + } + + meta_data.extend(request_hash_map) + }; + meta_data +} + #[cfg(test)] mod test_validate_shipping_address_against_payment_method { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 61917fdcd2e..5b05e601502 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1440,6 +1440,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ Some(RequestIncrementalAuthorization::True) | Some(RequestIncrementalAuthorization::Default) ), + metadata: payment_data.payment_intent.metadata.clone(), }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 0809ca17820..531ca849a35 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -591,6 +591,7 @@ pub struct SetupMandateRequestData { pub return_url: Option<String>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, + pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)]
feat
[Stripe] Metadata to connector metadata mapping (#3295)
4397c8e19977974510f7c24daa8c3ef7f2ab907b
2023-05-03 01:57:14
Nishant Joshi
fix(refund_sync): add validation for missing `connector_refund_id` (#1013)
false
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index ce41f3195d9..cf36c9c1fe0 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -48,6 +48,11 @@ pub struct RefundRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +#[derive(Default, Debug, Clone, Deserialize)] +pub struct RefundsRetrieveBody { + pub force_sync: Option<bool>, +} + #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. @@ -58,6 +63,10 @@ pub struct RefundsRetrieveRequest { )] pub refund_id: String, + /// `force_sync` with the connector to get refund details + /// (defaults to false) + pub force_sync: Option<bool>, + /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 0e8bf6af83b..644a50e5786 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -99,6 +99,7 @@ pub async fn refund_retrieve( ) -> HttpResponse { let refund_request = refund_types::RefundsRetrieveRequest { refund_id: path.into_inner(), + force_sync: Some(true), merchant_connector_details: None, }; wrap::compatibility_api_wrap::< diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 822dde6cf89..5797edcd620 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -292,6 +292,7 @@ pub trait RefundsRequestData { } impl RefundsRequestData for types::RefundsData { + #[track_caller] fn get_connector_refund_id(&self) -> Result<String, Error> { self.connector_refund_id .clone() @@ -373,6 +374,7 @@ impl CardData for api::Card { } } +#[track_caller] fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { for (k, v) in CARD_REGEX.iter() { let regex: Regex = v diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 7942c8e6a6e..e72f4cc021b 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -318,19 +318,39 @@ pub async fn refund_retrieve_core( .await .transpose()?; - response = sync_refund_with_gateway( - state, - &merchant_account, - &payment_attempt, - &payment_intent, - &refund, - creds_identifier, - ) - .await?; + response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { + sync_refund_with_gateway( + state, + &merchant_account, + &payment_attempt, + &payment_intent, + &refund, + creds_identifier, + ) + .await + } else { + Ok(refund) + }?; Ok(response) } +fn should_call_refund(refund: &storage_models::refund::Refund, force_sync: bool) -> bool { + // This implies, we cannot perform a refund sync & `the connector_refund_id` + // doesn't exist + let predicate1 = refund.connector_refund_id.is_some(); + + // This allows refund sync at connector level if force_sync is enabled, or + // checks if the refund has failed + let predicate2 = force_sync + || !matches!( + refund.refund_status, + storage_models::enums::RefundStatus::Failure + ); + + predicate1 && predicate2 +} + #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &AppState, @@ -755,6 +775,7 @@ pub async fn sync_refund_with_gateway_workflow( merchant_account, refunds::RefundsRetrieveRequest { refund_id: refund_core.refund_internal_reference_id, + force_sync: Some(true), merchant_connector_details: None, }, ) diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index cd593dd30c1..a2090e34193 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -164,6 +164,7 @@ async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( merchant_account.clone(), api_models::refunds::RefundsRetrieveRequest { refund_id: refund_id.to_owned(), + force_sync: Some(true), merchant_connector_details: None, }, ) diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index ea3af93648b..ae13ff36fd9 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -65,9 +65,11 @@ pub async fn refunds_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, + query_params: web::Query<api_models::refunds::RefundsRetrieveBody>, ) -> HttpResponse { let refund_request = refunds::RefundsRetrieveRequest { refund_id: path.into_inner(), + force_sync: query_params.force_sync, merchant_connector_details: None, }; let flow = Flow::RefundsRetrieve;
fix
add validation for missing `connector_refund_id` (#1013)
7607b6b67153fce1e965d7ef7e41c62380884d8f
2023-07-27 10:34:35
Kritik Modi
feat(router): Validate payment method type in payments request against given payment method data for non-card flows (#1236)
false
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6f421a752dc..a38c3677fd3 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -37,6 +37,7 @@ use crate::{ types::{self, AsyncLift}, }, storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update}, + transformers::ForeignInto, ErrorResponse, RouterData, }, utils::{ @@ -1371,6 +1372,18 @@ pub(crate) fn validate_payment_method_fields_present( }, )?; + utils::when( + !matches!( + req.payment_method, + Some(api_enums::PaymentMethod::Card) | None + ) && (req.payment_method_type.is_none()), + || { + Err(errors::ApiErrorResponse::MissingRequiredField { + field_name: "payment_method_type", + }) + }, + )?; + utils::when( req.payment_method.is_some() && req.payment_method_data.is_none() @@ -1382,6 +1395,56 @@ pub(crate) fn validate_payment_method_fields_present( }, )?; + let payment_method: Option<api_enums::PaymentMethod> = + (req.payment_method_type).map(ForeignInto::foreign_into); + + utils::when( + req.payment_method.is_some() + && req.payment_method_type.is_some() + && (req.payment_method != payment_method), + || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: ("payment_method_type doesn't correspond to the specified payment_method" + .to_string()), + }) + }, + )?; + + utils::when( + !matches!( + req.payment_method + .as_ref() + .zip(req.payment_method_data.as_ref()), + Some( + ( + api_enums::PaymentMethod::Card, + api::PaymentMethodData::Card(..) + ) | ( + api_enums::PaymentMethod::Wallet, + api::PaymentMethodData::Wallet(..) + ) | ( + api_enums::PaymentMethod::PayLater, + api::PaymentMethodData::PayLater(..) + ) | ( + api_enums::PaymentMethod::BankRedirect, + api::PaymentMethodData::BankRedirect(..) + ) | ( + api_enums::PaymentMethod::BankDebit, + api::PaymentMethodData::BankDebit(..) + ) | ( + api_enums::PaymentMethod::Crypto, + api::PaymentMethodData::Crypto(..) + ) + ) | None + ), + || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "payment_method_data doesn't correspond to the specified payment_method" + .to_string(), + }) + }, + )?; + Ok(()) }
feat
Validate payment method type in payments request against given payment method data for non-card flows (#1236)
cd7040fa8cad2e69a53e3ed609c9eb8a8a17495a
2024-03-05 05:46:21
github-actions
chore(postman): update Postman collection files
false
diff --git a/postman/collection-json/aci.postman_collection.json b/postman/collection-json/aci.postman_collection.json index 9d58d212f97..6bf1ad2b1d6 100644 --- a/postman/collection-json/aci.postman_collection.json +++ b/postman/collection-json/aci.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": [ diff --git a/postman/collection-json/adyen_uk.postman_collection.json b/postman/collection-json/adyen_uk.postman_collection.json index 08cf0761e4e..1092f8bb71e 100644 --- a/postman/collection-json/adyen_uk.postman_collection.json +++ b/postman/collection-json/adyen_uk.postman_collection.json @@ -90,14 +90,7 @@ ], "request": { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": [ diff --git a/postman/collection-json/airwallex.postman_collection.json b/postman/collection-json/airwallex.postman_collection.json index 7a0d9164e92..f2e804f2b3e 100644 --- a/postman/collection-json/airwallex.postman_collection.json +++ b/postman/collection-json/airwallex.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": [ diff --git a/postman/collection-json/authorizedotnet.postman_collection.json b/postman/collection-json/authorizedotnet.postman_collection.json index 8130f1fd9a1..4008c4f9cee 100644 --- a/postman/collection-json/authorizedotnet.postman_collection.json +++ b/postman/collection-json/authorizedotnet.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": [ diff --git a/postman/collection-json/bambora.postman_collection.json b/postman/collection-json/bambora.postman_collection.json index d9161f7929c..b6e689790ee 100644 --- a/postman/collection-json/bambora.postman_collection.json +++ b/postman/collection-json/bambora.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": [ diff --git a/postman/collection-json/bambora_3ds.postman_collection.json b/postman/collection-json/bambora_3ds.postman_collection.json index ca4999c9dfd..0d908b26bf8 100644 --- a/postman/collection-json/bambora_3ds.postman_collection.json +++ b/postman/collection-json/bambora_3ds.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": [ diff --git a/postman/collection-json/bankofamerica.postman_collection.json b/postman/collection-json/bankofamerica.postman_collection.json index 752b77dcd15..1850cee8b60 100644 --- a/postman/collection-json/bankofamerica.postman_collection.json +++ b/postman/collection-json/bankofamerica.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": [ diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json index fa6c9258b8d..adb18e9970f 100644 --- a/postman/collection-json/bluesnap.postman_collection.json +++ b/postman/collection-json/bluesnap.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": [ diff --git a/postman/collection-json/braintree.postman_collection.json b/postman/collection-json/braintree.postman_collection.json index dce605f85c7..96879450ee9 100644 --- a/postman/collection-json/braintree.postman_collection.json +++ b/postman/collection-json/braintree.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": [ diff --git a/postman/collection-json/checkout.postman_collection.json b/postman/collection-json/checkout.postman_collection.json index d510b1c2a17..aedd67ecfa8 100644 --- a/postman/collection-json/checkout.postman_collection.json +++ b/postman/collection-json/checkout.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": [ diff --git a/postman/collection-json/forte.postman_collection.json b/postman/collection-json/forte.postman_collection.json index 8297b4778f4..96a64d519e7 100644 --- a/postman/collection-json/forte.postman_collection.json +++ b/postman/collection-json/forte.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": [ diff --git a/postman/collection-json/globalpay.postman_collection.json b/postman/collection-json/globalpay.postman_collection.json index 2a2d27a87ca..205275b052a 100644 --- a/postman/collection-json/globalpay.postman_collection.json +++ b/postman/collection-json/globalpay.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": [ diff --git a/postman/collection-json/hyperswitch.postman_collection.json b/postman/collection-json/hyperswitch.postman_collection.json index 0acf2ee2b3f..57186715422 100644 --- a/postman/collection-json/hyperswitch.postman_collection.json +++ b/postman/collection-json/hyperswitch.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": [ diff --git a/postman/collection-json/mollie.postman_collection.json b/postman/collection-json/mollie.postman_collection.json index f956058b5ca..e2649a261fa 100644 --- a/postman/collection-json/mollie.postman_collection.json +++ b/postman/collection-json/mollie.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": [ diff --git a/postman/collection-json/multisafepay.postman_collection.json b/postman/collection-json/multisafepay.postman_collection.json index 50a2655c5b0..290a321fcfc 100644 --- a/postman/collection-json/multisafepay.postman_collection.json +++ b/postman/collection-json/multisafepay.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": [ diff --git a/postman/collection-json/nexinets.postman_collection.json b/postman/collection-json/nexinets.postman_collection.json index cb74918d194..aa0c435f498 100644 --- a/postman/collection-json/nexinets.postman_collection.json +++ b/postman/collection-json/nexinets.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": [ diff --git a/postman/collection-json/payme.postman_collection.json b/postman/collection-json/payme.postman_collection.json index 280a131386e..5451f143cb3 100644 --- a/postman/collection-json/payme.postman_collection.json +++ b/postman/collection-json/payme.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": [ diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json index 83f27e69dc5..a4a64bde153 100644 --- a/postman/collection-json/paypal.postman_collection.json +++ b/postman/collection-json/paypal.postman_collection.json @@ -81,14 +81,7 @@ ], "request": { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": [ diff --git a/postman/collection-json/powertranz.postman_collection.json b/postman/collection-json/powertranz.postman_collection.json index ad81a38c1f0..b158827bbb7 100644 --- a/postman/collection-json/powertranz.postman_collection.json +++ b/postman/collection-json/powertranz.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": [ diff --git a/postman/collection-json/rapyd.postman_collection.json b/postman/collection-json/rapyd.postman_collection.json index b3d6a9416f8..39ea3aab24c 100644 --- a/postman/collection-json/rapyd.postman_collection.json +++ b/postman/collection-json/rapyd.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": [ diff --git a/postman/collection-json/shift4.postman_collection.json b/postman/collection-json/shift4.postman_collection.json index 13b4f25c3c6..196dcbcb30b 100644 --- a/postman/collection-json/shift4.postman_collection.json +++ b/postman/collection-json/shift4.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": [ diff --git a/postman/collection-json/trustpay.postman_collection.json b/postman/collection-json/trustpay.postman_collection.json index cacc015851d..1203cd1793e 100644 --- a/postman/collection-json/trustpay.postman_collection.json +++ b/postman/collection-json/trustpay.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": [ diff --git a/postman/collection-json/volt.postman_collection.json b/postman/collection-json/volt.postman_collection.json index 78d4e9d6ea4..011173f9ff8 100644 --- a/postman/collection-json/volt.postman_collection.json +++ b/postman/collection-json/volt.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": [ diff --git a/postman/collection-json/wise.postman_collection.json b/postman/collection-json/wise.postman_collection.json index 410f066ff6f..f7d47298085 100644 --- a/postman/collection-json/wise.postman_collection.json +++ b/postman/collection-json/wise.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": [ diff --git a/postman/collection-json/worldline.postman_collection.json b/postman/collection-json/worldline.postman_collection.json index 7b1a9d027ba..c8e7969b766 100644 --- a/postman/collection-json/worldline.postman_collection.json +++ b/postman/collection-json/worldline.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": [ diff --git a/postman/collection-json/zen.postman_collection.json b/postman/collection-json/zen.postman_collection.json index 067cd0840a3..54ce9e9e98f 100644 --- a/postman/collection-json/zen.postman_collection.json +++ b/postman/collection-json/zen.postman_collection.json @@ -58,14 +58,7 @@ "type": "noauth" }, "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": [
chore
update Postman collection files
45882bdb76f7f031776aa10692fabd792627b891
2025-02-10 03:03:23
awasthi21
feat(connector): [DATATRANS] Add Support for External 3DS (#7226)
false
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index a0e606e0741..2e1fd195b90 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -416,12 +416,11 @@ impl Connector { | Self::Razorpay | Self::Riskified | Self::Threedsecureio - | Self::Datatrans | Self::Netcetera | Self::CtpMastercard | Self::Noon | Self::Stripe => false, - Self::Checkout | Self::Nmi | Self::Cybersource => true, + Self::Checkout | Self::Nmi |Self::Datatrans|Self::Cybersource => true, } } diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans.rs b/crates/hyperswitch_connectors/src/connectors/datatrans.rs index b549f48984e..6c311dd4a98 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans.rs @@ -223,7 +223,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = self.base_url(connectors); - if req.is_three_ds() { + if req.is_three_ds() && req.request.authentication_data.is_none() { Ok(format!("{base_url}v1/transactions")) } else { Ok(format!("{base_url}v1/transactions/authorize")) diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs index c0f4ed22722..d2ca3d2d013 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs @@ -136,7 +136,7 @@ pub struct PlainCardDetails { pub cvv: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "3D")] - pub three_ds: Option<ThreedsInfo>, + pub three_ds: Option<ThreeDSecureData>, } #[derive(Serialize, Clone, Debug)] @@ -144,6 +144,26 @@ pub struct ThreedsInfo { cardholder: CardHolder, } +#[derive(Serialize, Clone, Debug)] +#[serde(untagged)] +pub enum ThreeDSecureData { + Cardholder(ThreedsInfo), + Authentication(ThreeDSData), +} +#[derive(Debug, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDSData { + #[serde(rename = "threeDSTransactionId")] + pub three_ds_transaction_id: Secret<String>, + pub cavv: Secret<String>, + pub eci: Option<String>, + pub xid: Secret<String>, + #[serde(rename = "threeDSVersion")] + pub three_ds_version: String, + #[serde(rename = "authenticationResponse")] + pub authentication_response: String, +} + #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardHolder { @@ -240,13 +260,16 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> card: create_card_details(item, &req_card)?, refno: item.router_data.connector_request_reference_id.clone(), auto_settle: item.router_data.request.is_auto_capture()?, - redirect: match item.router_data.is_three_ds() { - true => Some(RedirectUrls { + redirect: if item.router_data.is_three_ds() + && item.router_data.request.authentication_data.is_none() + { + Some(RedirectUrls { success_url: item.router_data.request.router_return_url.clone(), cancel_url: item.router_data.request.router_return_url.clone(), error_url: item.router_data.request.router_return_url.clone(), - }), - false => None, + }) + } else { + None }, }), PaymentMethodData::Wallet(_) @@ -314,9 +337,23 @@ fn create_card_details( three_ds: None, }; - if item.router_data.is_three_ds() { + if let Some(auth_data) = &item.router_data.request.authentication_data { + details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData { + three_ds_transaction_id: Secret::new(auth_data.threeds_server_transaction_id.clone()), + cavv: Secret::new(auth_data.cavv.clone()), + eci: auth_data.eci.clone(), + xid: Secret::new( + auth_data + .ds_trans_id + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "xid" })?, + ), + three_ds_version: auth_data.message_version.to_string(), + authentication_response: "Y".to_string(), + })); + } else if item.router_data.is_three_ds() { let billing = item.router_data.get_billing_address()?; - details.three_ds = Some(ThreedsInfo { + details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo { cardholder: CardHolder { cardholder_name: item.router_data.get_billing_full_name()?, email: item.router_data.request.get_email()?, @@ -326,7 +363,7 @@ fn create_card_details( bill_addr_state: billing.get_state().ok().cloned(), bill_addr_country: billing.get_country().ok().copied(), }, - }); + })); } Ok(details) }
feat
[DATATRANS] Add Support for External 3DS (#7226)
05080259132fb12cdef40a999bd02b6fe2beeeaa
2024-10-01 15:55:43
Anurag Thakur
refactor(connector): Move connector Dlocal and Square from router to hyperswitch_connector crate (#6156)
false
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index f057b7d4a33..9406353a1ee 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -4,6 +4,7 @@ pub mod cashtocode; pub mod coinbase; pub mod cryptopay; pub mod deutschebank; +pub mod dlocal; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -13,6 +14,7 @@ pub mod mollie; pub mod nexixpay; pub mod novalnet; pub mod powertranz; +pub mod square; pub mod stax; pub mod taxjar; pub mod thunes; @@ -22,8 +24,8 @@ pub mod worldline; pub use self::{ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase, - cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea, - fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, - novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes, - tsys::Tsys, volt::Volt, worldline::Worldline, + cryptopay::Cryptopay, deutschebank::Deutschebank, dlocal::Dlocal, fiserv::Fiserv, + fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, + nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, square::Square, stax::Stax, + taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, }; diff --git a/crates/router/src/connector/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs similarity index 68% rename from crates/router/src/connector/dlocal.rs rename to crates/hyperswitch_connectors/src/connectors/dlocal.rs index dc99619e9da..78d3ad4f63e 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs @@ -2,36 +2,51 @@ pub mod transformers; use std::fmt::Debug; +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::enums; use common_utils::{ crypto::{self, SignMessage}, date_time, - request::RequestContent, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, }; -use diesel_models::enums; use error_stack::{report, ResultExt}; use hex::encode; -use masking::PeekInterface; -use transformers as dlocal; - -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, logger, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, - utils::BytesExt, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{Mask, Maskable, PeekInterface}; +use transformers as dlocal; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self}, +}; #[derive(Debug, Clone)] pub struct Dlocal; @@ -54,9 +69,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let dlocal_req = self.get_request_body(req, connectors)?; let date = date_time::date_as_yyyymmddthhmmssmmmz() @@ -110,7 +125,7 @@ impl ConnectorCommon for Dlocal { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.dlocal.base_url.as_ref() } @@ -148,49 +163,30 @@ impl ConnectorValidation for Dlocal { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Dlocal +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Dlocal { // Not Implemented (R) } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Dlocal -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Dlocal -{ +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string()) .into(), @@ -198,14 +194,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -215,16 +209,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}secure_payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = dlocal::DlocalRouterData::try_from(( &self.get_currency_unit(), @@ -238,12 +232,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) @@ -260,11 +254,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_authorize_response=?res); + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_authorize_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsAuthorizeResponse") @@ -273,7 +267,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -290,14 +284,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -307,8 +299,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let sync_data = dlocal::DlocalPaymentsSyncRequest::try_from(req)?; Ok(format!( @@ -320,12 +312,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) @@ -343,18 +335,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payment_sync_response=?res); + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payment_sync_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal 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 { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -363,14 +355,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -380,16 +370,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + _req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = dlocal::DlocalPaymentsCaptureRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -397,12 +387,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -417,18 +407,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_capture_response=?res); + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_capture_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal 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 { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -445,14 +435,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -462,8 +450,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, + req: &PaymentsCancelRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let cancel_data = dlocal::DlocalPaymentsCancelRequest::try_from(req)?; Ok(format!( @@ -475,12 +463,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) @@ -490,11 +478,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_cancel_response=?res); + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_cancel_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsCancelResponse") @@ -502,7 +490,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -519,12 +507,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Dlocal { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dlocal { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -534,16 +522,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}refunds", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = dlocal::DlocalRouterData::try_from(( &self.get_currency_unit(), @@ -557,11 +545,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn build_request( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( @@ -576,18 +564,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(dlocal_refund_response=?res); + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + router_env::logger::debug!(dlocal_refund_response=?res); let response: dlocal::RefundResponse = res.response .parse_struct("Dlocal RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -604,12 +592,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Dlocal { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dlocal { fn get_headers( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -619,8 +607,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let sync_data = dlocal::DlocalRefundsSyncRequest::try_from(req)?; Ok(format!( @@ -632,12 +620,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -647,18 +635,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - logger::debug!(dlocal_refund_sync_response=?res); + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_refund_sync_response=?res); let response: dlocal::RefundResponse = res .response .parse_struct("Dlocal 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 { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -676,24 +664,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for Dlocal { +impl webhooks::IncomingWebhook for Dlocal { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::EventNotSupported) + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { + Ok(IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs similarity index 77% rename from crates/router/src/connector/dlocal/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs index a613cdb2054..385601294b3 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs @@ -1,15 +1,23 @@ use api_models::payments::AddressDetails; -use common_utils::pii::Email; +use common_enums::enums; +use common_utils::{pii::Email, request::Method}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::{refunds::Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + types, +}; +use hyperswitch_interfaces::{api::CurrencyUnit, errors}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - services, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _}, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] @@ -57,16 +65,11 @@ pub struct DlocalRouterData<T> { pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> { +impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, router_data): ( - &api::CurrencyUnit, - enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -100,7 +103,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP let country = address.get_country()?; let name = get_payer_name(address); match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { + PaymentMethodData::Card(ref ccard) => { let should_capture = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) @@ -143,38 +146,34 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP }), order_id: item.router_data.connector_request_reference_id.clone(), three_dsecure: match item.router_data.auth_type { - diesel_models::enums::AuthenticationType::ThreeDs => { + enums::AuthenticationType::ThreeDs => { Some(ThreeDSecureReqData { force: true }) } - diesel_models::enums::AuthenticationType::NoThreeDs => None, + enums::AuthenticationType::NoThreeDs => None, }, callback_url: Some(item.router_data.request.get_router_return_url()?), description: item.router_data.description.clone(), }; Ok(payment_request) } - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - crate::connector::utils::get_unimplemented_payment_method_error_message( - "Dlocal", - ), - ))? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Dlocal"), + ))?, } } } @@ -252,10 +251,10 @@ pub struct DlocalAuthType { pub(super) secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for DlocalAuthType { +impl TryFrom<&ConnectorAuthType> for DlocalAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::SignatureKey { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, @@ -309,24 +308,21 @@ pub struct DlocalPaymentsResponse { order_id: Option<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .three_dsecure .and_then(|three_secure_data| three_secure_data.redirect_url) - .map(|redirect_url| { - services::RedirectForm::from((redirect_url, services::Method::Get)) - }); + .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get))); - let response = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + let response = PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, @@ -350,24 +346,17 @@ pub struct DlocalPaymentsSyncResponse { order_id: Option<String>, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsSyncResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -388,24 +377,17 @@ pub struct DlocalPaymentsCaptureResponse { order_id: Option<String>, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsCaptureResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -424,26 +406,17 @@ pub struct DlocalPaymentsCancelResponse { order_id: String, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsCancelResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsCancelResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -509,16 +482,16 @@ pub struct RefundResponse { pub status: RefundStatus, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), @@ -545,16 +518,14 @@ impl TryFrom<&types::RefundSyncRouterData> for DlocalRefundsSyncRequest { } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), diff --git a/crates/router/src/connector/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs similarity index 65% rename from crates/router/src/connector/square.rs rename to crates/hyperswitch_connectors/src/connectors/square.rs index 9b9c68a5f2b..bf2cd4e1ace 100644 --- a/crates/router/src/connector/square.rs +++ b/crates/hyperswitch_connectors/src/connectors/square.rs @@ -2,31 +2,54 @@ pub mod transformers; use std::fmt::Debug; -use api_models::enums; +use api_models::{ + enums, + webhooks::{IncomingWebhookEvent, ObjectReferenceId}, +}; use base64::Engine; -use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::ResultExt; -use masking::PeekInterface; -use transformers as square; - -use super::utils::{self as super_utils, RefundsRequestData}; -use crate::{ - configs::settings, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + AuthorizeSessionToken, }, + router_request_types::{ + AccessTokenRequestData, AuthorizeSessionTokenData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, + PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, - utils::BytesExt, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + consts, errors, + events::connector_api_logs::ConnectorEvent, + types::{self, PaymentsAuthorizeType, Response}, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask, Maskable, PeekInterface}; +use transformers::{ + self as square, SquareAuthType, SquarePaymentsRequest, SquareRefundRequest, SquareTokenRequest, +}; + +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self, get_header_key_value, RefundsRequestData}, }; #[derive(Debug, Clone)] @@ -52,12 +75,12 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; @@ -76,15 +99,15 @@ impl ConnectorCommon for Square { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.square.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth = square::SquareAuthType::try_from(auth_type) + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let auth = SquareAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), @@ -142,39 +165,24 @@ impl ConnectorValidation for Square { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - super::utils::construct_not_implemented_error_report(capture_method, self.id()), + utils::construct_not_implemented_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Square { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Square -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Square {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Square -{ +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Square { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Square".to_string()) .into(), @@ -183,18 +191,14 @@ impl } #[async_trait::async_trait] -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Square +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Square { fn get_headers( &self, - _req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + _req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), types::TokenizationType::get_content_type(self) @@ -209,8 +213,8 @@ impl fn get_url( &self, - _req: &types::TokenizationRouterData, - connectors: &settings::Connectors, + _req: &TokenizationRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/card-nonce", @@ -224,22 +228,22 @@ impl fn get_request_body( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, + req: &TokenizationRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquareTokenRequest::try_from(req)?; + let connector_req = SquareTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::TokenizationType::get_headers(self, req, connectors)?) @@ -252,12 +256,12 @@ impl fn handle_response( &self, - data: &types::TokenizationRouterData, + data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> + ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: square::SquareTokenResponse = res .response @@ -267,7 +271,7 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -282,21 +286,17 @@ impl } } -impl - ConnectorIntegration< - api::AuthorizeSessionToken, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData, - > for Square +impl ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> + for Square { fn get_headers( &self, - _req: &types::PaymentsAuthorizeSessionTokenRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + _req: &PaymentsAuthorizeSessionTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]) @@ -308,10 +308,10 @@ impl fn get_url( &self, - req: &types::PaymentsAuthorizeSessionTokenRouterData, - connectors: &settings::Connectors, + req: &PaymentsAuthorizeSessionTokenRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let auth = square::SquareAuthType::try_from(&req.connector_auth_type) + let auth = SquareAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( @@ -327,12 +327,12 @@ impl fn build_request( &self, - req: &types::PaymentsAuthorizeSessionTokenRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeSessionTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsPreAuthorizeType::get_url( self, req, connectors, )?) @@ -346,10 +346,10 @@ impl fn handle_response( &self, - data: &types::PaymentsAuthorizeSessionTokenRouterData, + data: &PaymentsAuthorizeSessionTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: square::SquareSessionResponse = res .response .parse_struct("SquareSessionResponse") @@ -358,7 +358,7 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -374,14 +374,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -391,38 +389,34 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquarePaymentsRequest::try_from(req)?; + let connector_req = SquarePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -431,10 +425,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsAuthorizeResponse") @@ -443,7 +437,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -459,14 +453,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -476,8 +468,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request @@ -493,12 +485,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) @@ -508,10 +500,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsSyncResponse") @@ -520,7 +512,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -536,14 +528,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -553,8 +543,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/complete", @@ -565,9 +555,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { if req.request.amount_to_capture != req.request.payment_amount { Err(errors::ConnectorError::NotSupported { message: "Partial Capture".to_string(), @@ -575,8 +565,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme })? } Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -588,10 +578,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsCaptureResponse") @@ -600,7 +590,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -616,14 +606,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -633,8 +621,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, + req: &PaymentsCancelRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/cancel", @@ -645,12 +633,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) @@ -660,10 +648,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsVoidResponse") @@ -672,7 +660,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -688,12 +676,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Square { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -703,28 +691,28 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/refunds", self.base_url(connectors),)) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquareRefundRequest::try_from(req)?; + let connector_req = SquareRefundRequest::try_from(req)?; 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) + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( @@ -739,10 +727,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundResponse") @@ -751,7 +739,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -767,12 +755,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Square { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -782,8 +770,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/refunds/{}", @@ -794,12 +782,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -809,10 +797,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundSyncResponse") @@ -821,7 +809,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -838,10 +826,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for Square { +impl IncomingWebhook for Square { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(common_utils::crypto::HmacSha256)) @@ -849,12 +837,12 @@ impl api::IncomingWebhook for Square { fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let encoded_signature = - super_utils::get_header_key_value("x-square-hmacsha256-signature", request.headers)?; - let signature = consts::BASE64_ENGINE + get_header_key_value("x-square-hmacsha256-signature", request.headers)?; + let signature = common_utils::consts::BASE64_ENGINE .decode(encoded_signature) .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; Ok(signature) @@ -862,7 +850,7 @@ impl api::IncomingWebhook for Square { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -885,43 +873,37 @@ impl api::IncomingWebhook for Square { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { let webhook_body: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match webhook_body.data.object { - square::SquareWebhookObject::Payment(_) => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - webhook_body.data.id, - ), - )) - } - square::SquareWebhookObject::Refund(_) => { - Ok(api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id), - )) - } + square::SquareWebhookObject::Payment(_) => Ok(ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.data.id), + )), + square::SquareWebhookObject::Refund(_) => Ok(ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id), + )), } } fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let details: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(details.data.object)) + Ok(IncomingWebhookEvent::from(details.data.object)) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: square::SquareWebhookBody = request diff --git a/crates/router/src/connector/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs similarity index 59% rename from crates/router/src/connector/square/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/square/transformers.rs index db7058f3384..4e2b30a574b 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -1,38 +1,44 @@ +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::enums; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::{BankDebitData, Card, PayLaterData, PaymentMethodData, WalletData}, + router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, + router_flow_types::{refunds::Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types, +}; +use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, + utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _}, }; -impl TryFrom<(&types::TokenizationRouterData, domain::BankDebitData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: (&types::TokenizationRouterData, domain::BankDebitData), + value: (&types::TokenizationRouterData, BankDebitData), ) -> Result<Self, Self::Error> { let (_item, bank_debit_data) = value; match bank_debit_data { - domain::BankDebitData::AchBankDebit { .. } - | domain::BankDebitData::SepaBankDebit { .. } - | domain::BankDebitData::BecsBankDebit { .. } - | domain::BankDebitData::BacsBankDebit { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + BankDebitData::AchBankDebit { .. } + | BankDebitData::SepaBankDebit { .. } + | BankDebitData::BecsBankDebit { .. } + | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } -impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, Card)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - value: (&types::TokenizationRouterData, domain::Card), - ) -> Result<Self, Self::Error> { + fn try_from(value: (&types::TokenizationRouterData, Card)) -> Result<Self, Self::Error> { let (item, card_data) = value; let auth = SquareAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; @@ -69,63 +75,59 @@ impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequ } } -impl TryFrom<(&types::TokenizationRouterData, domain::PayLaterData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: (&types::TokenizationRouterData, domain::PayLaterData), + value: (&types::TokenizationRouterData, PayLaterData), ) -> Result<Self, Self::Error> { let (_item, pay_later_data) = value; match pay_later_data { - domain::PayLaterData::AfterpayClearpayRedirect { .. } - | domain::PayLaterData::KlarnaRedirect { .. } - | domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::AffirmRedirect { .. } - | domain::PayLaterData::PayBrightRedirect { .. } - | domain::PayLaterData::WalleyRedirect { .. } - | domain::PayLaterData::AlmaRedirect { .. } - | domain::PayLaterData::AtomeRedirect { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PayLaterData::AfterpayClearpayRedirect { .. } + | PayLaterData::KlarnaRedirect { .. } + | PayLaterData::KlarnaSdk { .. } + | PayLaterData::AffirmRedirect { .. } + | PayLaterData::PayBrightRedirect { .. } + | PayLaterData::WalleyRedirect { .. } + | PayLaterData::AlmaRedirect { .. } + | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } -impl TryFrom<(&types::TokenizationRouterData, domain::WalletData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - value: (&types::TokenizationRouterData, domain::WalletData), - ) -> Result<Self, Self::Error> { + fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> { let (_item, wallet_data) = value; match wallet_data { - domain::WalletData::ApplePay(_) - | domain::WalletData::GooglePay(_) - | domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayRedirect(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::PaypalRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::WeChatPayQr(_) - | domain::WalletData::CashappQr(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + WalletData::ApplePay(_) + | WalletData::GooglePay(_) + | WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), ))?, } @@ -156,31 +158,27 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - domain::PaymentMethodData::BankDebit(bank_debit_data) => { + PaymentMethodData::BankDebit(bank_debit_data) => { Self::try_from((item, bank_debit_data)) } - domain::PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)), - domain::PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)), - domain::PaymentMethodData::PayLater(pay_later_data) => { - Self::try_from((item, pay_later_data)) - } - domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)), + PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)), + PaymentMethodData::PayLater(pay_later_data) => Self::try_from((item, pay_later_data)), + PaymentMethodData::GiftCard(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -191,18 +189,17 @@ pub struct SquareSessionResponse { session_id: Secret<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Pending, session_token: Some(item.response.session_id.clone().expose()), - response: Ok(types::PaymentsResponseData::SessionTokenResponse { + response: Ok(PaymentsResponseData::SessionTokenResponse { session_token: item.response.session_id.expose(), }), ..item.data @@ -215,16 +212,15 @@ pub struct SquareTokenResponse { card_nonce: Secret<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TokenizationResponse { + response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.card_nonce.expose(), }), ..item.data @@ -258,13 +254,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let autocomplete = item.request.is_auto_capture()?; match item.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(_) => { + PaymentMethodData::Card(_) => { let pm_token = item.get_payment_method_token()?; Ok(Self { idempotency_key: Secret::new(item.attempt_id.clone()), source_id: match pm_token { - types::PaymentMethodToken::Token(token) => token, - types::PaymentMethodToken::ApplePayDecrypt(_) => Err( + PaymentMethodToken::Token(token) => token, + PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Square"), )?, }, @@ -279,26 +275,24 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { }, }) } - domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PaymentMethodData::BankDebit(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -309,21 +303,21 @@ pub struct SquareAuthType { pub(super) key1: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { +impl TryFrom<&ConnectorAuthType> for SquareAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self { 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 { .. } - | types::ConnectorAuthType::CertificateAuth { .. } => { + ConnectorAuthType::HeaderKey { .. } + | ConnectorAuthType::SignatureKey { .. } + | ConnectorAuthType::MultiAuthKey { .. } + | ConnectorAuthType::CurrencyAuthKey { .. } + | ConnectorAuthType::TemporaryAuth { .. } + | ConnectorAuthType::NoKey { .. } + | ConnectorAuthType::CertificateAuth { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } @@ -364,13 +358,12 @@ pub struct SquarePaymentsResponse { payment: SquarePaymentsResponseDetails, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { //Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status. let status = enums::AttemptStatus::from(item.response.payment.status); @@ -380,8 +373,8 @@ impl<F, T> }; Ok(Self { status, - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -448,15 +441,15 @@ pub struct RefundResponse { refund: SquareRefundResponseDetails, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.refund.id, refund_status: enums::RefundStatus::from(item.response.refund.status), }), @@ -465,15 +458,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.refund.id, refund_status: enums::RefundStatus::from(item.response.refund.status), }), @@ -513,7 +504,7 @@ pub struct SquareWebhookBody { pub data: SquareWebhookData, } -impl From<SquareWebhookObject> for api::IncomingWebhookEvent { +impl From<SquareWebhookObject> for IncomingWebhookEvent { fn from(item: SquareWebhookObject) -> Self { match item { SquareWebhookObject::Payment(payment_data) => match payment_data.status { diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 4c27e11fc45..5b71a1bd29c 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -12,7 +12,11 @@ pub(crate) mod headers { pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; + pub(crate) const X_DATE: &str = "X-Date"; + pub(crate) const X_LOGIN: &str = "X-Login"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; + pub(crate) const X_TRANS_KEY: &str = "X-Trans-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; + pub(crate) const X_VERSION: &str = "X-Version"; } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 31052ab0df2..0d43c263f97 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -95,6 +95,7 @@ default_imp_for_authorize_session_token!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -132,10 +133,12 @@ default_imp_for_calculate_tax!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, connectors::Stax, + connectors::Square, connectors::Novalnet, connectors::Mollie, connectors::Nexixpay, @@ -169,10 +172,12 @@ default_imp_for_session_update!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Mollie, connectors::Novalnet, @@ -208,6 +213,7 @@ default_imp_for_complete_authorize!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -216,6 +222,7 @@ default_imp_for_complete_authorize!( connectors::Novalnet, connectors::Nexixpay, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -245,6 +252,7 @@ default_imp_for_incremental_authorization!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -255,6 +263,7 @@ default_imp_for_incremental_authorization!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -284,6 +293,7 @@ default_imp_for_create_customer!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -293,6 +303,7 @@ default_imp_for_create_customer!( connectors::Novalnet, connectors::Nexixpay, connectors::Powertranz, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -323,6 +334,7 @@ default_imp_for_connector_redirect_response!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -331,6 +343,7 @@ default_imp_for_connector_redirect_response!( connectors::Nexixpay, connectors::Powertranz, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -360,6 +373,7 @@ default_imp_for_pre_processing_steps!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -370,6 +384,7 @@ default_imp_for_pre_processing_steps!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -399,6 +414,7 @@ default_imp_for_post_processing_steps!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -409,6 +425,7 @@ default_imp_for_post_processing_steps!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -438,6 +455,7 @@ default_imp_for_approve!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -448,6 +466,7 @@ default_imp_for_approve!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -477,6 +496,7 @@ default_imp_for_reject!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -487,6 +507,7 @@ default_imp_for_reject!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -516,6 +537,7 @@ default_imp_for_webhook_source_verification!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -526,6 +548,7 @@ default_imp_for_webhook_source_verification!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -556,6 +579,7 @@ default_imp_for_accept_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -566,6 +590,7 @@ default_imp_for_accept_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -595,6 +620,7 @@ default_imp_for_submit_evidence!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -605,6 +631,7 @@ default_imp_for_submit_evidence!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -634,6 +661,7 @@ default_imp_for_defend_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -644,6 +672,7 @@ default_imp_for_defend_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -682,6 +711,7 @@ default_imp_for_file_upload!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -692,6 +722,7 @@ default_imp_for_file_upload!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -723,6 +754,7 @@ default_imp_for_payouts_create!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -733,6 +765,7 @@ default_imp_for_payouts_create!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -764,6 +797,7 @@ default_imp_for_payouts_retrieve!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -774,6 +808,7 @@ default_imp_for_payouts_retrieve!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -805,6 +840,7 @@ default_imp_for_payouts_eligibility!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -815,6 +851,7 @@ default_imp_for_payouts_eligibility!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -846,6 +883,7 @@ default_imp_for_payouts_fulfill!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -856,6 +894,7 @@ default_imp_for_payouts_fulfill!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -887,6 +926,7 @@ default_imp_for_payouts_cancel!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -897,6 +937,7 @@ default_imp_for_payouts_cancel!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -928,6 +969,7 @@ default_imp_for_payouts_quote!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -938,6 +980,7 @@ default_imp_for_payouts_quote!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -969,6 +1012,7 @@ default_imp_for_payouts_recipient!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -979,6 +1023,7 @@ default_imp_for_payouts_recipient!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1010,6 +1055,7 @@ default_imp_for_payouts_recipient_account!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1020,6 +1066,7 @@ default_imp_for_payouts_recipient_account!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1051,6 +1098,7 @@ default_imp_for_frm_sale!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1061,6 +1109,7 @@ default_imp_for_frm_sale!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1092,6 +1141,7 @@ default_imp_for_frm_checkout!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1102,6 +1152,7 @@ default_imp_for_frm_checkout!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1133,6 +1184,7 @@ default_imp_for_frm_transaction!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1143,6 +1195,7 @@ default_imp_for_frm_transaction!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1174,6 +1227,7 @@ default_imp_for_frm_fulfillment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1184,6 +1238,7 @@ default_imp_for_frm_fulfillment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1215,6 +1270,7 @@ default_imp_for_frm_record_return!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1225,6 +1281,7 @@ default_imp_for_frm_record_return!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1253,6 +1310,7 @@ default_imp_for_revoking_mandates!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1263,6 +1321,7 @@ default_imp_for_revoking_mandates!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 16e592688ac..d4e1836ac5f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -202,6 +202,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -212,6 +213,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -242,6 +244,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -252,6 +255,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -277,6 +281,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -287,6 +292,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -318,6 +324,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -328,6 +335,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -358,6 +366,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -368,6 +377,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -398,6 +408,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -408,6 +419,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -448,6 +460,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -458,6 +471,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -490,6 +504,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -500,6 +515,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -532,6 +548,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -542,6 +559,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -574,6 +592,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -584,6 +603,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -616,6 +636,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -626,6 +647,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -658,6 +680,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -668,6 +691,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -700,6 +724,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -710,6 +735,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -742,6 +768,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -752,6 +779,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -784,6 +812,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -794,6 +823,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -824,6 +854,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -834,6 +865,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -866,6 +898,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -876,6 +909,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -908,6 +942,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -918,6 +953,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -950,6 +986,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -960,6 +997,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -992,6 +1030,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1002,6 +1041,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1034,6 +1074,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1044,6 +1085,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1073,6 +1115,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1083,6 +1126,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 3d47afb9b82..a6be862403d 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -1,14 +1,15 @@ use crate::{ router_data::{AccessToken, RouterData}, router_flow_types::{ - AccessTokenAuth, Authorize, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, Void, + AccessTokenAuth, Authorize, AuthorizeSessionToken, CalculateTax, Capture, + CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, + Void, }, router_request_types::{ - AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData, - PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, - SetupMandateRequestData, + AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, + ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, + RefundsData, SetupMandateRequestData, }, router_response_types::{ PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, @@ -17,6 +18,8 @@ use crate::{ pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsAuthorizeSessionTokenRouterData = + RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 116fc67320f..390d5de1513 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -12,7 +12,6 @@ pub mod braintree; pub mod checkout; pub mod cybersource; pub mod datatrans; -pub mod dlocal; #[cfg(feature = "dummy_connector")] pub mod dummyconnector; pub mod ebanx; @@ -46,7 +45,6 @@ pub mod razorpay; pub mod riskified; pub mod shift4; pub mod signifyd; -pub mod square; pub mod stripe; pub mod threedsecureio; pub mod trustpay; @@ -61,11 +59,11 @@ pub mod zsl; pub use hyperswitch_connectors::connectors::{ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode, coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank, - deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, - nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, - stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, - volt::Volt, worldline, worldline::Worldline, + deutschebank::Deutschebank, dlocal, dlocal::Dlocal, fiserv, fiserv::Fiserv, fiservemea, + fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, + mollie, mollie::Mollie, nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, + powertranz::Powertranz, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, + thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] @@ -74,14 +72,13 @@ pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout, - cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte, + cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, - square::Square, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, - wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, - zen::Zen, zsl::Zsl, + stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargo::Wellsfargo, + wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, zen::Zen, zsl::Zsl, }; 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 3ff93cf9bf0..5c350f3a475 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -685,7 +685,6 @@ default_imp_for_new_connector_integration_payment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -715,7 +714,6 @@ default_imp_for_new_connector_integration_payment!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -760,7 +758,6 @@ default_imp_for_new_connector_integration_refund!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -790,7 +787,6 @@ default_imp_for_new_connector_integration_refund!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -829,7 +825,6 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -859,7 +854,6 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -920,7 +914,6 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -950,7 +943,6 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -993,7 +985,6 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1023,7 +1014,6 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1050,7 +1040,6 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1080,7 +1069,6 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1134,7 +1122,6 @@ default_imp_for_new_connector_integration_file_upload!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1164,7 +1151,6 @@ default_imp_for_new_connector_integration_file_upload!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1297,7 +1283,6 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1327,7 +1312,6 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1373,7 +1357,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1403,7 +1386,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1449,7 +1431,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1479,7 +1460,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1525,7 +1505,6 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1555,7 +1534,6 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1601,7 +1579,6 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1631,7 +1608,6 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1677,7 +1653,6 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1707,7 +1682,6 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1753,7 +1727,6 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1784,7 +1757,6 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Riskified, connector::Signifyd, connector::Stripe, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1829,7 +1801,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1859,7 +1830,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1903,7 +1873,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1933,7 +1902,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2066,7 +2034,6 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2096,7 +2063,6 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2142,7 +2108,6 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2172,7 +2137,6 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2218,7 +2182,6 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2248,7 +2211,6 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2294,7 +2256,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2324,7 +2285,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2370,7 +2330,6 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2400,7 +2359,6 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2443,7 +2401,6 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2473,7 +2430,6 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 79ed9e25259..677c7968f45 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -211,7 +211,6 @@ default_imp_for_complete_authorize!( connector::Boku, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Gocardless, @@ -235,7 +234,6 @@ default_imp_for_complete_authorize!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -287,7 +285,6 @@ default_imp_for_webhook_source_verification!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -318,7 +315,6 @@ default_imp_for_webhook_source_verification!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -372,7 +368,6 @@ default_imp_for_create_customer!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -403,7 +398,6 @@ default_imp_for_create_customer!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Wellsfargo, @@ -453,7 +447,6 @@ default_imp_for_connector_redirect_response!( connector::Boku, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Gocardless, @@ -478,7 +471,6 @@ default_imp_for_connector_redirect_response!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -618,7 +610,6 @@ default_imp_for_accept_dispute!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -650,7 +641,6 @@ default_imp_for_accept_dispute!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -724,7 +714,6 @@ default_imp_for_file_upload!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -755,7 +744,6 @@ default_imp_for_file_upload!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Opennode, @@ -807,7 +795,6 @@ default_imp_for_submit_evidence!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -838,7 +825,6 @@ default_imp_for_submit_evidence!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Opennode, @@ -890,7 +876,6 @@ default_imp_for_defend_dispute!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Globalpay, connector::Forte, @@ -921,7 +906,6 @@ default_imp_for_defend_dispute!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -988,7 +972,6 @@ default_imp_for_pre_processing_steps!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Iatapay, connector::Itaubank, @@ -1014,7 +997,6 @@ default_imp_for_pre_processing_steps!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -1059,7 +1041,6 @@ default_imp_for_post_processing_steps!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Iatapay, connector::Itaubank, @@ -1083,7 +1064,6 @@ default_imp_for_post_processing_steps!( connector::Rapyd, connector::Riskified, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -1218,7 +1198,6 @@ default_imp_for_payouts_create!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1247,7 +1226,6 @@ default_imp_for_payouts_create!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1301,7 +1279,6 @@ default_imp_for_payouts_retrieve!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1332,7 +1309,6 @@ default_imp_for_payouts_retrieve!( connector::Riskified, connector::Signifyd, connector::Stripe, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1389,7 +1365,6 @@ default_imp_for_payouts_eligibility!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1419,7 +1394,6 @@ default_imp_for_payouts_eligibility!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1471,7 +1445,6 @@ default_imp_for_payouts_fulfill!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1499,7 +1472,6 @@ default_imp_for_payouts_fulfill!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1552,7 +1524,6 @@ default_imp_for_payouts_cancel!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1582,7 +1553,6 @@ default_imp_for_payouts_cancel!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1636,7 +1606,6 @@ default_imp_for_payouts_quote!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1666,7 +1635,6 @@ default_imp_for_payouts_quote!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1721,7 +1689,6 @@ default_imp_for_payouts_recipient!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1751,7 +1718,6 @@ default_imp_for_payouts_recipient!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1808,7 +1774,6 @@ default_imp_for_payouts_recipient_account!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1839,7 +1804,6 @@ default_imp_for_payouts_recipient_account!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1893,7 +1857,6 @@ default_imp_for_approve!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1924,7 +1887,6 @@ default_imp_for_approve!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1979,7 +1941,6 @@ default_imp_for_reject!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2010,7 +1971,6 @@ default_imp_for_reject!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2155,7 +2115,6 @@ default_imp_for_frm_sale!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2184,7 +2143,6 @@ default_imp_for_frm_sale!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2241,7 +2199,6 @@ default_imp_for_frm_checkout!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2270,7 +2227,6 @@ default_imp_for_frm_checkout!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2327,7 +2283,6 @@ default_imp_for_frm_transaction!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2356,7 +2311,6 @@ default_imp_for_frm_transaction!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2413,7 +2367,6 @@ default_imp_for_frm_fulfillment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2442,7 +2395,6 @@ default_imp_for_frm_fulfillment!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2499,7 +2451,6 @@ default_imp_for_frm_record_return!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2528,7 +2479,6 @@ default_imp_for_frm_record_return!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2582,7 +2532,6 @@ default_imp_for_incremental_authorization!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2613,7 +2562,6 @@ default_imp_for_incremental_authorization!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2664,7 +2612,6 @@ default_imp_for_revoking_mandates!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2694,7 +2641,6 @@ default_imp_for_revoking_mandates!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2906,7 +2852,6 @@ default_imp_for_authorize_session_token!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2988,7 +2933,6 @@ default_imp_for_calculate_tax!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -3018,7 +2962,6 @@ default_imp_for_calculate_tax!( connector::Rapyd, connector::Razorpay, connector::Riskified, - connector::Square, connector::Signifyd, connector::Stripe, connector::Shift4, @@ -3072,7 +3015,6 @@ default_imp_for_session_update!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -3102,7 +3044,6 @@ default_imp_for_session_update!( connector::Rapyd, connector::Razorpay, connector::Riskified, - connector::Square, connector::Signifyd, connector::Stripe, connector::Shift4,
refactor
Move connector Dlocal and Square from router to hyperswitch_connector crate (#6156)
e659e7029e758ef46b4fd12b262a58d0c3f5e5c0
2023-09-08 15:13:49
Sakil Mostak
refactor(connector): [Stripe] Using `connector_request_reference_id` as object_reference_id for Webhooks (#2064)
false
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 3e8c31ef661..b7cb260cb7b 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -1733,14 +1733,38 @@ impl api::IncomingWebhook for Stripe { Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent => { - api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - details.event_data.event_object.id, + match details.event_data.event_object.metadata { + // if order_id is present + Some(meta_data) => api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId(meta_data.order_id), ), - ) + // else used connector_transaction_id + None => api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + details.event_data.event_object.id, + ), + ), + } } - - stripe::WebhookEventObjectType::Charge | stripe::WebhookEventObjectType::Dispute => { + stripe::WebhookEventObjectType::Charge => { + match details.event_data.event_object.metadata { + // if order_id is present + Some(meta_data) => api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId(meta_data.order_id), + ), + // else used connector_transaction_id + None => api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + details + .event_data + .event_object + .payment_intent + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + ), + } + } + stripe::WebhookEventObjectType::Dispute => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details @@ -1759,11 +1783,31 @@ impl api::IncomingWebhook for Stripe { ) } stripe::WebhookEventObjectType::Refund => { - api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::ConnectorRefundId( - details.event_data.event_object.id, + match details.event_data.event_object.metadata { + // if meta_data is present + Some(meta_data) => { + // Issue: 2076 + match meta_data.is_refund_id_as_reference { + // if the order_id is refund_id + Some(_) => api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::RefundId(meta_data.order_id), + ), + // if the order_id is payment_id + // since payment_id was being passed before the deployment of this pr + _ => api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId( + details.event_data.event_object.id, + ), + ), + } + } + // else use connector_transaction_id + None => api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId( + details.event_data.event_object.id, + ), ), - ) + } } }) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index ef23f4ddab2..9dc6689f466 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -96,12 +96,8 @@ pub struct PaymentIntentRequest { pub currency: String, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, - #[serde(rename = "metadata[order_id]")] - pub metadata_order_id: String, - #[serde(rename = "metadata[txn_id]")] - pub metadata_txn_id: String, - #[serde(rename = "metadata[txn_uuid]")] - pub metadata_txn_uuid: String, + #[serde(flatten)] + pub meta_data: StripeMetadata, pub return_url: String, pub confirm: bool, pub mandate: Option<Secret<String>>, @@ -124,6 +120,21 @@ pub struct PaymentIntentRequest { pub payment_method_types: Option<StripePaymentMethodType>, } +// Field rename is required only in case of serialization as it is passed in the request to the connector. +// Deserialization is happening only in case of webhooks, where fields name should be used as defined in the struct. +// Whenever adding new fields, Please ensure it doesn't break the webhook flow +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct StripeMetadata { + // merchant_reference_id + #[serde(rename(serialize = "metadata[order_id]"))] + pub order_id: String, + // to check whether the order_id is refund_id or payemnt_id + // before deployment, order id is set to payemnt_id in refunds but now it is set as refund_id + // it is set as string instead of bool because stripe pass it as string even if we set it as bool + #[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))] + pub is_refund_id_as_reference: Option<String>, +} + #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SetupIntentRequest { #[serde(rename = "metadata[order_id]")] @@ -1537,9 +1548,7 @@ impl TryFrom<&payments::GooglePayWalletData> for StripePaymentMethodData { impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let metadata_order_id = item.connector_request_reference_id.clone(); - let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); - let metadata_txn_uuid = Uuid::new_v4().to_string(); //Fetch autogenerated txn_uuid from Database. + let order_id = item.connector_request_reference_id.clone(); let shipping_address = match item.address.shipping.clone() { Some(mut shipping) => StripeShippingAddress { @@ -1720,9 +1729,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(), statement_descriptor: item.request.statement_descriptor.clone(), - metadata_order_id, - metadata_txn_id, - metadata_txn_uuid, + meta_data: StripeMetadata { + order_id, + is_refund_id_as_reference: None, + }, return_url: item .request .router_return_url @@ -1838,13 +1848,6 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { } } -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] -pub struct StripeMetadata { - pub order_id: String, - pub txn_id: String, - pub txn_uuid: String, -} - #[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { @@ -2505,31 +2508,26 @@ pub struct BacsFinancialDetails { // REFUND : // Type definition for Stripe RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Debug, Serialize)] pub struct RefundRequest { pub amount: Option<i64>, //amount in cents, hence passed as integer pub payment_intent: String, - #[serde(rename = "metadata[order_id]")] - pub metadata_order_id: String, - #[serde(rename = "metadata[txn_id]")] - pub metadata_txn_id: String, - #[serde(rename = "metadata[txn_uuid]")] - pub metadata_txn_uuid: String, + #[serde(flatten)] + pub meta_data: StripeMetadata, } impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { let amount = item.request.refund_amount; - let metadata_txn_id = "Fetch txn_id from DB".to_string(); - let metadata_txn_uuid = "Fetch txn_id from DB".to_string(); let payment_intent = item.request.connector_transaction_id.clone(); Ok(Self { amount: Some(amount), payment_intent, - metadata_order_id: item.payment_id.clone(), - metadata_txn_id, - metadata_txn_uuid, + meta_data: StripeMetadata { + order_id: item.request.refund_id.clone(), + is_refund_id_as_reference: Some("true".to_string()), + }, }) } } @@ -3037,6 +3035,7 @@ pub struct WebhookEventObjectData { pub created: PrimitiveDateTime, pub evidence_details: Option<EvidenceDetails>, pub status: Option<WebhookEventStatus>, + pub metadata: Option<StripeMetadata>, } #[derive(Debug, Deserialize, strum::Display)]
refactor
[Stripe] Using `connector_request_reference_id` as object_reference_id for Webhooks (#2064)
7e44bbca63c1818c0fabdf2734d9b0ae5d639fe1
2024-05-17 15:57:30
Vrishab Srivatsa
feat: added client_source, client_version in payment_attempt from payments confirm request headers (#4657)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7c15f145e2f..f00be78a039 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -540,9 +540,11 @@ impl RequestSurchargeDetails { } } -#[derive(Default, Debug, Clone, Copy)] +#[derive(Default, Debug, Clone)] pub struct HeaderPayload { pub payment_confirm_source: Option<api_enums::PaymentSource>, + pub client_source: Option<String>, + pub client_version: Option<String>, pub x_hs_latency: Option<bool>, } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d4d2ddaef03..ffa9aee1153 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -70,6 +70,8 @@ pub struct PaymentAttempt { pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, } impl PaymentAttempt { @@ -150,6 +152,8 @@ pub struct PaymentAttemptNew { pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, } impl PaymentAttemptNew { @@ -233,6 +237,8 @@ pub enum PaymentAttemptUpdate { authentication_connector: Option<String>, authentication_id: Option<String>, payment_method_billing_address_id: Option<String>, + client_source: Option<String>, + client_version: Option<String>, }, VoidUpdate { status: storage_enums::AttemptStatus, @@ -388,6 +394,8 @@ pub struct PaymentAttemptUpdateInternal { authentication_id: Option<String>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, + client_source: Option<String>, + client_version: Option<String>, } impl PaymentAttemptUpdateInternal { @@ -453,6 +461,8 @@ impl PaymentAttemptUpdate { authentication_id, payment_method_billing_address_id, fingerprint_id, + client_source, + client_version, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -501,6 +511,8 @@ impl PaymentAttemptUpdate { payment_method_billing_address_id: payment_method_billing_address_id .or(source.payment_method_billing_address_id), fingerprint_id: fingerprint_id.or(source.fingerprint_id), + client_source: client_source.or(source.client_source), + client_version: client_version.or(source.client_version), ..source } } @@ -587,6 +599,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_billing_address_id, fingerprint_id, payment_method_id, + client_source, + client_version, } => Self { amount: Some(amount), currency: Some(currency), @@ -616,6 +630,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { fingerprint_id, payment_method_id, capture_method, + client_source, + client_version, ..Default::default() }, PaymentAttemptUpdate::VoidUpdate { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 427f9560e03..61022f2f253 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -778,6 +778,10 @@ diesel::table! { fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_billing_address_id -> Nullable<Varchar>, + #[max_length = 64] + client_source -> Nullable<Varchar>, + #[max_length = 64] + client_version -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 93beeff57d2..298d82cf31e 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -73,6 +73,8 @@ pub struct PaymentAttemptBatchNew { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, } #[allow(dead_code)] @@ -133,6 +135,8 @@ impl PaymentAttemptBatchNew { mandate_data: self.mandate_data, payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + client_source: self.client_source, + client_version: self.client_version, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index d6565a6be60..fe6f3711e39 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -166,6 +166,8 @@ pub struct PaymentAttempt { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, } impl PaymentAttempt { @@ -249,6 +251,8 @@ pub struct PaymentAttemptNew { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, } impl PaymentAttemptNew { @@ -327,6 +331,8 @@ pub enum PaymentAttemptUpdate { payment_method_billing_address_id: Option<String>, fingerprint_id: Option<String>, payment_method_id: Option<String>, + client_source: Option<String>, + client_version: Option<String>, }, RejectUpdate { status: storage_enums::AttemptStatus, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1b47c267af1..76cd1307d89 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -294,7 +294,7 @@ where call_connector_action.clone(), &validate_result, schedule_time, - header_payload, + header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] @@ -364,7 +364,7 @@ where call_connector_action.clone(), &validate_result, schedule_time, - header_payload, + header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] @@ -497,7 +497,7 @@ where frm_info.and_then(|info| info.suggested_action), #[cfg(not(feature = "frm"))] None, - header_payload, + header_payload.clone(), ) .await?; } @@ -528,7 +528,7 @@ where None, &key_store, None, - header_payload, + header_payload.clone(), ) .await?; } @@ -785,7 +785,7 @@ where call_connector_action, auth_flow, eligible_routable_connectors, - header_payload, + header_payload.clone(), ) .await?; @@ -1579,7 +1579,7 @@ where updated_customer, key_store, frm_suggestion, - header_payload, + header_payload.clone(), ) .await?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 853b3d64adc..b4dd06b8ce9 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3554,6 +3554,8 @@ impl AttemptType { // New payment method billing address can be passed for a retry payment_method_billing_address_id: None, fingerprint_id: None, + client_source: None, + client_version: None, } } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index a0062fb81c3..7d1858bd0d7 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1069,6 +1069,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.payment_attempt.amount); + let client_source = header_payload + .client_source + .clone() + .or(payment_data.payment_attempt.client_source.clone()); + let client_version = header_payload + .client_version + .clone() + .or(payment_data.payment_attempt.client_version.clone()); + let m_payment_data_payment_attempt = payment_data.payment_attempt.clone(); let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let m_browser_info = browser_info.clone(); @@ -1136,6 +1145,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_method_billing_address_id, fingerprint_id: m_fingerprint_id, payment_method_id: m_payment_method_id, + client_source, + client_version, }, storage_scheme, ) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0c68289fb5f..b12b5ec4600 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -930,6 +930,8 @@ impl PaymentCreate { fingerprint_id: None, authentication_connector: None, authentication_id: None, + client_source: None, + client_version: None, }, additional_pm_data, )) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 77ec848fb44..1fd76130597 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -19,6 +19,7 @@ use crate::{ payments::{self, helpers}, utils as core_utils, }, + headers::X_PAYMENT_CONFIRM_SOURCE, routes::{metrics, AppState}, services::{self, RedirectForm}, types::{ @@ -488,7 +489,7 @@ where .unwrap_or_default(); if let Some(payment_confirm_source) = payment_intent.payment_confirm_source { headers.push(( - "payment_confirm_source".to_string(), + X_PAYMENT_CONFIRM_SOURCE.to_string(), Maskable::new_normal(payment_confirm_source.to_string()), )) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 27c9c7d2dd4..2e9ecc13dcb 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -72,6 +72,9 @@ pub mod headers { pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; + pub const X_CLIENT_VERSION: &str = "X-Client-Version"; + pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; + pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 6a1b424a330..06bdd3ed05a 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -497,7 +497,7 @@ pub async fn payments_confirm( req_state, auth.merchant_account, auth.key_store, - header_payload, + header_payload.clone(), req, auth_flow, ) diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 423a1ee90a6..6fb98d944bf 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -18,6 +18,7 @@ use masking::{ExposeInterface, PeekInterface}; use super::domain; use crate::{ core::errors, + headers::{X_CLIENT_SOURCE, X_CLIENT_VERSION, X_PAYMENT_CONFIRM_SOURCE}, services::authentication::get_header_value_by_key, types::{ api::{self as api_types, routing as routing_types}, @@ -1011,7 +1012,7 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { let payment_confirm_source: Option<api_enums::PaymentSource> = - get_header_value_by_key("payment_confirm_source".into(), headers)? + get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)? .map(|source| { source .to_owned() @@ -1038,8 +1039,17 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers) .map(|value| value == Some("true")) .unwrap_or(false); + + let client_source = + get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string()); + + let client_version = + get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); + Ok(Self { payment_confirm_source, + client_source, + client_version, x_hs_latency: Some(x_hs_latency), }) } diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 33ef6d416f2..cc2f2abc004 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -157,6 +157,8 @@ impl PaymentAttemptInterface for MockDb { mandate_data: payment_attempt.mandate_data, payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id, fingerprint_id: payment_attempt.fingerprint_id, + client_source: payment_attempt.client_source, + client_version: payment_attempt.client_version, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index d090f646da3..d4709648c4f 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -410,6 +410,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .payment_method_billing_address_id .clone(), fingerprint_id: payment_attempt.fingerprint_id.clone(), + client_source: payment_attempt.client_source.clone(), + client_version: payment_attempt.client_version.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1164,6 +1166,8 @@ impl DataModelExt for PaymentAttempt { mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + client_source: self.client_source, + client_version: self.client_version, } } @@ -1228,6 +1232,8 @@ impl DataModelExt for PaymentAttempt { .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, + client_source: storage_model.client_source, + client_version: storage_model.client_version, } } } @@ -1290,6 +1296,8 @@ impl DataModelExt for PaymentAttemptNew { mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + client_source: self.client_source, + client_version: self.client_version, } } @@ -1352,6 +1360,8 @@ impl DataModelExt for PaymentAttemptNew { .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, + client_source: storage_model.client_source, + client_version: storage_model.client_version, } } } @@ -1470,6 +1480,8 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_connector, authentication_id, payment_method_billing_address_id, + client_source, + client_version, } => DieselPaymentAttemptUpdate::ConfirmUpdate { amount, currency, @@ -1498,6 +1510,8 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_connector, authentication_id, payment_method_billing_address_id, + client_source, + client_version, }, Self::VoidUpdate { status, @@ -1773,6 +1787,8 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_connector, authentication_id, payment_method_billing_address_id, + client_source, + client_version, } => Self::ConfirmUpdate { amount, currency, @@ -1801,6 +1817,8 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_connector, authentication_id, payment_method_billing_address_id, + client_source, + client_version, }, DieselPaymentAttemptUpdate::VoidUpdate { status, diff --git a/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/down.sql b/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/down.sql new file mode 100644 index 00000000000..5e91f5197d8 --- /dev/null +++ b/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS client_version; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS client_source; \ No newline at end of file diff --git a/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/up.sql b/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/up.sql new file mode 100644 index 00000000000..81584637c81 --- /dev/null +++ b/migrations/2024-05-15-133715_add_client_info_columns_in_payment_attempts/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS client_source VARCHAR(64) DEFAULT NULL; +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS client_version VARCHAR(64) DEFAULT NULL; \ No newline at end of file
feat
added client_source, client_version in payment_attempt from payments confirm request headers (#4657)
5a43da6a1a17ec636cb7010dab55f1e97c51d4b0
2022-12-18 11:39:24
Sanchith Hegde
ci: run tests on PRs with `S-awaiting-merge` label (#166)
false
diff --git a/.github/workflows/CI-skip-ignored-files.yml b/.github/workflows/CI-skip-ignored-files.yml index 04523b6f35f..f7b068ddd7d 100644 --- a/.github/workflows/CI-skip-ignored-files.yml +++ b/.github/workflows/CI-skip-ignored-files.yml @@ -4,16 +4,18 @@ name: CI on: pull_request: - paths: - - "config/**" - - "contrib/**" - - "docs/**" - - "monitoring/**" - - "openapi/**" - - "postman/**" - - "*.md" - - "LICENSE" - - "NOTICE" + types: + - "labeled" + - "opened" + - "ready_for_review" + - "reopened" + - "synchronize" + paths-ignore: + - ".github/workflows/**" + - "crates/**" + - "examples/**" + - "Cargo.lock" + - "Cargo.toml" concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -22,6 +24,7 @@ concurrency: jobs: formatting: name: Check formatting + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ubuntu-latest steps: - name: Skip formatting @@ -30,6 +33,7 @@ jobs: check-msrv: name: Check compilation on MSRV toolchain + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ${{ matrix.os }} strategy: matrix: @@ -42,6 +46,7 @@ jobs: # cargo-deny: # name: Run cargo-deny + # if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} # runs-on: ubuntu-latest # steps: # - name: Skip cargo-deny @@ -50,6 +55,7 @@ jobs: test: name: Run tests on stable toolchain + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ${{ matrix.os }} strategy: matrix: diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index d6d97f8b50f..72028f64032 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -4,28 +4,26 @@ on: push: branches: - main - paths-ignore: - - "config/**" - - "contrib/**" - - "docs/**" - - "monitoring/**" - - "openapi/**" - - "postman/**" - - "*.md" - - "LICENSE" - - "NOTICE" + paths: + - ".github/workflows/**" + - "crates/**" + - "examples/**" + - "Cargo.lock" + - "Cargo.toml" pull_request: - paths-ignore: - - "config/**" - - "contrib/**" - - "docs/**" - - "monitoring/**" - - "openapi/**" - - "postman/**" - - "*.md" - - "LICENSE" - - "NOTICE" + types: + - "labeled" + - "opened" + - "ready_for_review" + - "reopened" + - "synchronize" + paths: + - ".github/workflows/**" + - "crates/**" + - "examples/**" + - "Cargo.lock" + - "Cargo.toml" concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -56,6 +54,7 @@ env: jobs: formatting: name: Check formatting + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ubuntu-latest steps: - name: Checkout repository @@ -73,6 +72,7 @@ jobs: check-msrv: name: Check compilation on MSRV toolchain + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ${{ matrix.os }} strategy: fail-fast: true @@ -110,6 +110,7 @@ jobs: # cargo-deny: # name: Run cargo-deny + # if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} # runs-on: ubuntu-latest # strategy: # matrix: @@ -131,6 +132,7 @@ jobs: test: name: Run tests on stable toolchain + if: ${{ contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }} runs-on: ${{ matrix.os }} strategy: fail-fast: false
ci
run tests on PRs with `S-awaiting-merge` label (#166)
1d36798399c118f7cb7af93935123634e1afd6a0
2024-06-04 17:16:23
Sakil Mostak
feat(cypress): Add service level testing for Payouts (#4744)
false
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00001-CustomerCreate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00001-CustomerCreate.cy.js deleted file mode 100644 index 5e8bcb5aa14..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00001-CustomerCreate.cy.js +++ /dev/null @@ -1,22 +0,0 @@ -import customerCreateBody from "../../fixtures/create-customer-body.json"; -import State from "../../utils/State"; - -let globalState; - -describe("Customer Create flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - it("customer-create-call-test", () => { - - cy.createCustomerCallTest(customerCreateBody, globalState); - - }); -}); \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js deleted file mode 100644 index 4ee4483c961..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js +++ /dev/null @@ -1,206 +0,0 @@ -import captureBody from "../../fixtures/capture-flow-body.json"; -import confirmBody from "../../fixtures/confirm-body.json"; -import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - NoThreeDS Manual payment flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - NoThreeDS Manual Full Capture payment flow test", () => { - - context("payment Create and Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - }); - - context("Payment Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - }); - - - }); - - context("Card - NoThreeDS Manual Partial Capture payment flow test - Create and Confirm", () => { - - context("payment Create and Payment Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - }); - - context("payment + Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - }); - - - }); -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js deleted file mode 100644 index ef815777568..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js +++ /dev/null @@ -1,130 +0,0 @@ -import confirmBody from "../../fixtures/confirm-body.json"; -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import voidBody from "../../fixtures/void-payment-body.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - NoThreeDS Manual payment flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - void payment in Requires_capture state flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("void-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Void"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.voidCallTest(voidBody, req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - void payment in Requires_payment_method state flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("void-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Void"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.voidCallTest(voidBody, req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); }); - }); - - context("Card - void payment in Requires_payment_method state flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, false, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("void-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Void"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.voidCallTest(voidBody, req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); }); - }); -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js deleted file mode 100644 index 672c5cf8f4a..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js +++ /dev/null @@ -1,990 +0,0 @@ -import captureBody from "../../fixtures/capture-flow-body.json"; -import confirmBody from "../../fixtures/confirm-body.json"; -import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; -import citConfirmBody from "../../fixtures/create-mandate-cit.json"; -import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import refundBody from "../../fixtures/refund-flow-body.json"; -import listRefundCall from "../../fixtures/list-refund-call-body.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - Refund flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - - }) - - afterEach("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - Full Refund flow test for No-3DS", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - Partial Refund flow test for No-3DS", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Fully Refund Card-NoThreeDS payment flow test Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest( createConfirmPaymentBody, req_data, res_data,"no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - }); - - context("Partially Refund Card-NoThreeDS payment flow test Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest( createConfirmPaymentBody, req_data, res_data,"no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - Full Refund for fully captured No-3DS payment", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - Partial Refund for fully captured No-3DS payment", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - it("list-refund-call-test", () => { - cy.listRefundCallTest(listRefundCall, globalState); - }); - }); - - context("Card - Full Refund for partially captured No-3DS payment", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - partial Refund for partially captured No-3DS payment", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - Full Refund for Create + Confirm Automatic CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + req_data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 7000, true, "automatic", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 7000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - -}); - - context("Card - Full Refund flow test for 3DS", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - - }) - - afterEach("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - Partial Refund flow test for 3DS", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Fully Refund Card-ThreeDS payment flow test Create+Confirm", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - }); - - context("Partially Refund Card-ThreeDS payment flow test Create+Confirm", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - }); - - context("Card - Full Refund for fully captured 3DS payment", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - }); - - context("Card - Partial Refund for fully captured 3DS payment", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 5000, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 1500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - - }); - - context("Card - Full Refund for partially captured 3DS payment", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - - }); - - context("Card - partial Refund for partially captured 3DS payment", () => { - - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 50 , globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js deleted file mode 100644 index f0cdc9a6890..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js +++ /dev/null @@ -1,72 +0,0 @@ -import confirmBody from "../../fixtures/confirm-body.json"; -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import refundBody from "../../fixtures/refund-flow-body.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - Sync Refund flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Refund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("sync-refund-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SyncRefund"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.syncRefundCallTest(req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js deleted file mode 100644 index ec85017f55d..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js +++ /dev/null @@ -1,129 +0,0 @@ -import captureBody from "../../fixtures/capture-flow-body.json"; -import citConfirmBody from "../../fixtures/create-mandate-cit.json"; -import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - SingleUse Mandates flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 7000, true, "automatic", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - }); - - context("Card - NoThreeDS Create + Confirm Manual CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 6500, true, "manual", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("cit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 6500, true, "manual", globalState); - }); - - it("mit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("list-mandate-call-test", () => { - cy.listMandateCallTest(globalState); - }); - }); - - context("Card - ThreeDS Create + Confirm Manual CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Create No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 6500, true, "manual", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("cit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - - it("list-mandate-call-test", () => { - cy.listMandateCallTest(globalState); - }); - }); -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js deleted file mode 100644 index 3e14d69db88..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js +++ /dev/null @@ -1,138 +0,0 @@ -import captureBody from "../../fixtures/capture-flow-body.json"; -import citConfirmBody from "../../fixtures/create-mandate-cit.json"; -import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - MultiUse Mandates flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - - context("Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 7000, true, "automatic", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - }); - - context("Card - NoThreeDS Create + Confirm Manual CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 6500, true, "manual", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("cit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT 1", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 6500, true, "manual", globalState); - }); - - it("mit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT 2", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 6500, true, "manual", globalState); - }); - - it("mit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Card - ThreeDS Create + Confirm Manual CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 6500, true, "manual", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("cit-capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 6500, true, "automatic", globalState); - }); - }); -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js deleted file mode 100644 index 1f9782f2274..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js +++ /dev/null @@ -1,59 +0,0 @@ -import citConfirmBody from "../../fixtures/create-mandate-cit.json"; -import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -import State from "../../utils/State"; - -let globalState; - -describe("Card - SingleUse Mandates flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 7000, true, "automatic", "new_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - - it("list-mandate-call-test", () => { - cy.listMandateCallTest(globalState); - }); - - it("revoke-mandate-call-test", () => { - cy.revokeMandateCallTest(globalState); - }); - - it("revoke-revoked-mandate-call-test", () => { - cy.revokeMandateCallTest(globalState); - }); - }); - -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js deleted file mode 100644 index 828fb5101ac..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js +++ /dev/null @@ -1,187 +0,0 @@ -import captureBody from "../../fixtures/capture-flow-body.json"; -import confirmBody from "../../fixtures/confirm-body.json"; -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; -import customerCreateBody from "../../fixtures/create-customer-body.json"; -import SaveCardConfirmBody from "../../fixtures/save-card-confirm-body.json"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; -import State from "../../utils/State"; -let globalState; - -describe("Card - SaveCard payment flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - - context("Save card for NoThreeDS automatic capture payment- Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("customer-create-call-test", () => { - cy.createCustomerCallTest(customerCreateBody, globalState); - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest( createConfirmPaymentBody, req_data, res_data,"no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("retrieve-customerPM-call-test", () => { - cy.listCustomerPMCallTest(globalState); - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it ("confirm-save-card-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.saveCardConfirmCallTest(SaveCardConfirmBody, req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - }); - - context("Save card for NoThreeDS manual full capture payment- Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("customer-create-call-test", () => { - cy.createCustomerCallTest(customerCreateBody, globalState); - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest( createConfirmPaymentBody, req_data, res_data,"no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("retrieve-customerPM-call-test", () => { - cy.listCustomerPMCallTest(globalState); - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest( createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - - it ("confirm-save-card-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.saveCardConfirmCallTest(SaveCardConfirmBody, req_data, res_data, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - context("Save card for NoThreeDS manual partial capture payment- Create + Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("customer-create-call-test", () => { - cy.createCustomerCallTest(customerCreateBody, globalState); - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSAutoCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest( createConfirmPaymentBody, req_data, res_data,"no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("retrieve-customerPM-call-test", () => { - cy.listCustomerPMCallTest(globalState); - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest( createPaymentBody, req_data, res_data, "no_three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - - it ("confirm-save-card-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.saveCardConfirmCallTest(SaveCardConfirmBody,req_data, res_data,globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - }); - - -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js deleted file mode 100644 index 7a0eba4b6ad..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js +++ /dev/null @@ -1,68 +0,0 @@ -import citConfirmBody from "../../fixtures/create-mandate-cit.json"; -import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; -import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - SingleUse Mandates flow test", () => { - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - }) - - after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - NoThreeDS Create + Confirm Automatic CIT and Single use MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["ZeroAuthMandate"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 0, true, "automatic", "setup_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - }); - context("Card - NoThreeDS Create + Confirm Automatic CIT and Multi use MIT payment flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("Confirm No 3DS CIT", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["ZeroAuthMandate"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.citForMandatesCallTest(citConfirmBody, req_data, res_data, 0, true, "automatic", "setup_mandate", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - it("Confirm No 3DS MIT", () => { - cy.mitForMandatesCallTest(mitConfirmBody, 7000, true, "automatic", globalState); - }); - }); - -}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js deleted file mode 100644 index 50d136b5960..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js +++ /dev/null @@ -1,216 +0,0 @@ -import createPaymentBody from "../../fixtures/create-payment-body.json"; -import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; -import confirmBody from "../../fixtures/confirm-body.json"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import State from "../../utils/State"; -import captureBody from "../../fixtures/capture-flow-body.json"; -import * as utils from "../ConnectorUtils/utils"; - -let globalState; - -describe("Card - ThreeDS Manual payment flow test", () => { - - - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { - globalState = new State(state); - }) - - }) - - afterEach("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - - context("Card - ThreeDS Manual Full Capture payment flow test", () => { - context("payment Create and Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - }); - - context("Payment Create+Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = createConfirmPaymentBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["Capture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - }); - - - }); - - context("Card - ThreeDS Manual Partial Capture payment flow test - Create and Confirm", () => { - context("payment Create and Payment Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("confirm-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = confirmBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - }); - - context("payment + Confirm", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - beforeEach(function () { - if(!should_continue) { - this.skip(); - } - }); - - it("create+confirm-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "three_ds", "manual", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("Handle redirection", () => { - let expected_redirection = createConfirmPaymentBody["return_url"]; - cy.handleRedirection(globalState, expected_redirection); - }) - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - it("capture-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PartialCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); - }); - - it("retrieve-payment-call-test", () => { - cy.retrievePaymentCallTest(globalState); - }); - - }); - - - }); -}); diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js deleted file mode 100644 index 5b3df0efc5d..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js +++ /dev/null @@ -1,381 +0,0 @@ -const successfulNo3DSCardDetails = { - "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" - -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4000000000001091", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" -}; -export const connectorDetails = { - card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "succeeded", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 6500, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "partially_captured", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 100, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 200, - "body":{ - status: "cancelled" - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_customer_action" - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - } - }; diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js b/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js deleted file mode 100644 index 17e040668ad..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js +++ /dev/null @@ -1,425 +0,0 @@ -const successfulNo3DSCardDetails = { - "card_number": "4242424242424242", - "card_exp_month": "10", - "card_exp_year": "30", - "card_holder_name": "John", - "card_cvc": "737" -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4000000000001091", - "card_exp_month": "10", - "card_exp_year": "30", - "card_holder_name": "Joseph", - "card_cvc": "737" -}; - -export const connectorDetails = { - card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "succeeded", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 6500, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "partially_captured", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 100, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 200, - "body":{ - status: "cancelled" - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by bluesnap" - } - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 501, - "body": { - "error": { - "type": "invalid_request", - "message": "Setup Mandate flow for Bluesnap is not implemented", - "code": "IR_00", - } - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - } - }; \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js b/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js deleted file mode 100644 index 67d2875df5c..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js +++ /dev/null @@ -1,381 +0,0 @@ -const successfulNo3DSCardDetails = { - "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4000000000001091", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" -}; - -export const connectorDetails = { - card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "succeeded", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 6500, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "partially_captured", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 100, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 200, - "body":{ - status: "cancelled" - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_customer_action" - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - } - }; \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js b/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js deleted file mode 100644 index 27caaa82dc8..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js +++ /dev/null @@ -1,427 +0,0 @@ -const successfulNo3DSCardDetails = { - "card_number": "4000000000002503", - "card_exp_month": "08", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "999" -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4000000000002503", - "card_exp_month": "10", - "card_exp_year": "25", - "card_holder_name": "morino", - "card_cvc": "999" -}; - -export const connectorDetails = { - card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "processing", - "amount": 6500, - "amount_capturable": 6500, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "processing", - "amount": 6500, - "amount_capturable": 6500, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 400, - "body":{ - "error":{ - "code":"IR_16", - "message":"You cannot cancel this payment because it has status processing", - "type":"invalid_request", - } - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "pending", - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by nmi" - } - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 501, - "body": { - "error": { - "type": "invalid_request", - "message": "Setup Mandate flow for Nmi is not implemented", - "code": "IR_00", - } - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - } - }; \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js b/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js deleted file mode 100644 index 056b4b5e8ac..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js +++ /dev/null @@ -1,440 +0,0 @@ -const successfulNo3DSCardDetails = { - "card_number": "4012000033330026", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" - -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4868719460707704", - "card_exp_month": "01", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_cvc": "123" -}; - -export const connectorDetails = { - card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "processing", - "amount": 6500, - "amount_capturable": 6500, - "amount_received": 0, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "processing", - "amount": 6500, - "amount_capturable": 6500, - "amount_received": 0, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 200, - "body":{ - status: "cancelled" - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 400, - "body": { - "error": { - "type": "invalid_request", - "message": "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", - "code" : "IR_14" - }, - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 400, - "body": { - "error": { - "type": "invalid_request", - "message": "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", - "code" : "IR_14" - }, - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 400, - "body": { - "error": { - "type": "invalid_request", - "message": "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", - "code" : "IR_14" - }, - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 400, - "body":{ - "error": { - "type": "invalid_request", - "message": "Payment method type not supported", - "code": "HE_03", - "reason": "debit mandate payment is not supported by paypal" - } - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 501, - "body": { - "error": { - "type": "invalid_request", - "message": "Setup Mandate flow for Paypal is not implemented", - "code": "IR_00", - } - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "processing" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - } - }; - - diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js b/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js deleted file mode 100644 index 1003946dd73..00000000000 --- a/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js +++ /dev/null @@ -1,384 +0,0 @@ -const successfulTestCard = "4242424242424242"; -const successful3DSCard = "4000002760003184"; - -const successfulNo3DSCardDetails = { - "card_number": "4242424242424242", - "card_exp_month": "10", - "card_exp_year": "25", - "card_holder_name": "morino", - "card_cvc": "737" -}; - -const successfulThreeDSTestCardDetails = { - "card_number": "4000002760003184", - "card_exp_month": "10", - "card_exp_year": "25", - "card_holder_name": "morino", - "card_cvc": "737" -}; - -export const connectorDetails = { -card_pm:{ - "PaymentIntent": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_payment_method" - } - } - }, - "3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "No3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "No3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - "setup_future_usage": "on_session" - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "Capture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body":{ - "status": "succeeded", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 6500, - - } - } - }, - "PartialCapture": { - "Request": { - - }, - "Response": { - "status": 200, - "body": { - "status": "partially_captured", - "amount": 6500, - "amount_capturable": 0, - "amount_received": 100, - } - - } - }, - "Void":{ - "Request": { - }, - "Response": { - "status": 200, - "body":{ - status: "cancelled" - - } - } - }, - "Refund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "PartialRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "SyncRefund": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "customer_acceptance": null, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded", - } - - } - }, - "MandateSingleUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - - }, - "MandateSingleUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_customer_action" - } - } - - }, - "MandateSingleUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateSingleUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "MandateMultiUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSAutoCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "MandateMultiUse3DSManualCapture": { - "Request": { - "card": successfulThreeDSTestCardDetails, - "currency": "USD", - "mandate_type": { - "multi_use": { - "amount": 8000, - "currency": "USD" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, - "ZeroAuthMandate": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "mandate_type": { - "single_use": { - "amount": 8000, - "currency": "USD" - } - } - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSAutoCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "succeeded" - } - } - }, - "SaveCardUseNo3DSManualCapture": { - "Request": { - "card": successfulNo3DSCardDetails, - "currency": "USD", - "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" - } - }, - }, - "Response": { - "status": 200, - "body": { - "status": "requires_capture" - } - } - }, -} -}; \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/PaymentTest/00000-AccountCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00000-AccountCreate.cy.js new file mode 100644 index 00000000000..f58eb194db7 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00000-AccountCreate.cy.js @@ -0,0 +1,24 @@ +import apiKeyCreateBody from "../../fixtures/create-api-key-body.json"; +import merchantCreateBody from "../../fixtures/merchant-create-body.json"; +import State from "../../utils/State"; + +let globalState; +describe("Account Create flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + console.log("seeding globalState -> " + JSON.stringify(globalState)); + }); + }); + after("flush global state", () => { + console.log("flushing globalState -> " + JSON.stringify(globalState)); + cy.task("setGlobalState", globalState.data); + }); + + it("merchant-create-call-test", () => { + cy.merchantCreateCallTest(merchantCreateBody, globalState); + }); + it("api-key-create-call-test", () => { + cy.apiKeyCreateTest(apiKeyCreateBody, globalState); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00001-CustomerCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00001-CustomerCreate.cy.js new file mode 100644 index 00000000000..996ec85ee31 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00001-CustomerCreate.cy.js @@ -0,0 +1,20 @@ +import customerCreateBody from "../../fixtures/create-customer-body.json"; +import State from "../../utils/State"; + +let globalState; + +describe("Customer Create flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + console.log("seeding globalState -> " + JSON.stringify(globalState)); + }); + }); + after("flush global state", () => { + console.log("flushing globalState -> " + JSON.stringify(globalState)); + cy.task("setGlobalState", globalState.data); + }); + it("customer-create-call-test", () => { + cy.createCustomerCallTest(customerCreateBody, globalState); + }); +}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00002-ConnectorCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00002-ConnectorCreate.cy.js similarity index 78% rename from cypress-tests/cypress/e2e/ConnectorTest/00002-ConnectorCreate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00002-ConnectorCreate.cy.js index 927f0d02011..85a908da1a8 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00002-ConnectorCreate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00002-ConnectorCreate.cy.js @@ -3,17 +3,15 @@ import State from "../../utils/State"; let globalState; describe("Connector Account Create flow test", () => { - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { + cy.task("getGlobalState").then((state) => { globalState = new State(state); - }) - }) + }); + }); after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) + cy.task("setGlobalState", globalState.data); + }); it("connector-create-call-test", () => { cy.createConnectorCallTest(createConnectorBody, globalState); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00003-NoThreeDSAutoCapture.cy.js similarity index 60% rename from cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00003-NoThreeDSAutoCapture.cy.js index ec36fa16023..2dfedbb83d3 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00003-NoThreeDSAutoCapture.cy.js @@ -2,39 +2,47 @@ import confirmBody from "../../fixtures/confirm-body.json"; import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; import createPaymentBody from "../../fixtures/create-payment-body.json"; import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; let globalState; describe("Card - NoThreeDS payment flow test", () => { - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { + cy.task("getGlobalState").then((state) => { globalState = new State(state); - }) - }) + }); + }); after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) + cy.task("setGlobalState", globalState.data); + }); context("Card-NoThreeDS payment flow test Create and confirm", () => { let should_continue = true; // variable that will be used to skip tests if a previous test fails - beforeEach(function () { - if(!should_continue) { - this.skip(); - } + beforeEach(function () { + if (!should_continue) { + this.skip(); + } }); it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("payment_methods-call-test", () => { @@ -42,35 +50,47 @@ describe("Card - NoThreeDS payment flow test", () => { }); it("Confirm No 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; let req_data = data["Request"]; let res_data = data["Response"]; cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("retrieve-payment-call-test", () => { cy.retrievePaymentCallTest(globalState); }); - }); context("Card-NoThreeDS payment flow test Create+Confirm", () => { let should_continue = true; // variable that will be used to skip tests if a previous test fails - beforeEach(function () { - if(!should_continue) { - this.skip(); - } + beforeEach(function () { + if (!should_continue) { + this.skip(); + } }); it("create+confirm-payment-call-test", () => { console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.createConfirmPaymentTest(createConfirmPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("retrieve-payment-call-test", () => { diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00004-ThreeDSAutoCapture.cy.js similarity index 61% rename from cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00004-ThreeDSAutoCapture.cy.js index 3178170021c..7ae900c833a 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00004-ThreeDSAutoCapture.cy.js @@ -1,39 +1,46 @@ import confirmBody from "../../fixtures/confirm-body.json"; import createPaymentBody from "../../fixtures/create-payment-body.json"; import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; let globalState; describe("Card - ThreeDS payment flow test", () => { let should_continue = true; // variable that will be used to skip tests if a previous test fails - beforeEach(function () { - if(!should_continue) { - this.skip(); - } + beforeEach(function () { + if (!should_continue) { + this.skip(); + } }); before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { + cy.task("getGlobalState").then((state) => { globalState = new State(state); - }) - - }) + }); + }); afterEach("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) - + cy.task("setGlobalState", globalState.data); + }); it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("payment_methods-call-test", () => { @@ -41,16 +48,18 @@ describe("Card - ThreeDS payment flow test", () => { }); it("Confirm 3DS", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DSAutoCapture"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSAutoCapture" + ]; let req_data = data["Request"]; let res_data = data["Response"]; cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("Handle redirection", () => { let expected_redirection = confirmBody["return_url"]; cy.handleRedirection(globalState, expected_redirection); - }) - + }); }); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00005-NoThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00005-NoThreeDSManualCapture.cy.js new file mode 100644 index 00000000000..8fa262fd069 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00005-NoThreeDSManualCapture.cy.js @@ -0,0 +1,263 @@ +import captureBody from "../../fixtures/capture-flow-body.json"; +import confirmBody from "../../fixtures/confirm-body.json"; +import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - NoThreeDS Manual payment flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context("Card - NoThreeDS Manual Full Capture payment flow test", () => { + context("payment Create and Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + + context("Payment Create+Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + }); + + context( + "Card - NoThreeDS Manual Partial Capture payment flow test - Create and Confirm", + () => { + context("payment Create and Payment Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest( + confirmBody, + req_data, + res_data, + true, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + + context("payment + Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js new file mode 100644 index 00000000000..dea9d9e5406 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js @@ -0,0 +1,181 @@ +import confirmBody from "../../fixtures/confirm-body.json"; +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import voidBody from "../../fixtures/void-payment-body.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - NoThreeDS Manual payment flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context("Card - void payment in Requires_capture state flow test", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("void-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Void" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.voidCallTest(voidBody, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context( + "Card - void payment in Requires_payment_method state flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("void-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Void"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.voidCallTest(voidBody, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context( + "Card - void payment in Requires_payment_method state flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, false, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("void-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Void"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.voidCallTest(voidBody, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00007-SyncPayment.cy.js similarity index 62% rename from cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00007-SyncPayment.cy.js index 1920cdd09db..06e8b490ede 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00007-SyncPayment.cy.js @@ -1,36 +1,45 @@ import confirmBody from "../../fixtures/confirm-body.json"; import createPaymentBody from "../../fixtures/create-payment-body.json"; import State from "../../utils/State"; -import getConnectorDetails from "../ConnectorUtils/utils"; -import * as utils from "../ConnectorUtils/utils"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; let globalState; describe("Card - Sync payment flow test", () => { let should_continue = true; // variable that will be used to skip tests if a previous test fails - beforeEach(function () { - if(!should_continue) { - this.skip(); - } + beforeEach(function () { + if (!should_continue) { + this.skip(); + } }); before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { + cy.task("getGlobalState").then((state) => { globalState = new State(state); - }) - }) + }); + }); after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) + cy.task("setGlobalState", globalState.data); + }); it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["PaymentIntent"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.createPaymentIntentTest(createPaymentBody, req_data, res_data, "no_three_ds", "automatic", globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("payment_methods-call-test", () => { @@ -39,16 +48,18 @@ describe("Card - Sync payment flow test", () => { it("confirm-call-test", () => { console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DSAutoCapture"]; + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; let req_data = data["Request"]; let res_data = data["Response"]; console.log("det -> " + data.card); cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); - if(should_continue) should_continue = utils.should_continue_further(res_data); + if (should_continue) + should_continue = utils.should_continue_further(res_data); }); it("retrieve-payment-call-test", () => { cy.retrievePaymentCallTest(globalState); }); - }); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js new file mode 100644 index 00000000000..f2d921d80ff --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js @@ -0,0 +1,1304 @@ +import captureBody from "../../fixtures/capture-flow-body.json"; +import confirmBody from "../../fixtures/confirm-body.json"; +import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; +import citConfirmBody from "../../fixtures/create-mandate-cit.json"; +import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import refundBody from "../../fixtures/refund-flow-body.json"; +import listRefundCall from "../../fixtures/list-refund-call-body.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - Refund flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + afterEach("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context("Card - Full Refund flow test for No-3DS", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context("Card - Partial Refund flow test for No-3DS", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context( + "Fully Refund Card-NoThreeDS payment flow test Create+Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Refund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context( + "Partially Refund Card-NoThreeDS payment flow test Create+Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialRefund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialRefund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SyncRefund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context("Card - Full Refund for fully captured No-3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Capture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context("Card - Partial Refund for fully captured No-3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Capture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + it("list-refund-call-test", () => { + cy.listRefundCallTest(listRefundCall, globalState); + }); + }); + + context("Card - Full Refund for partially captured No-3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context("Card - partial Refund for partially captured No-3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context( + "Card - Full Refund for Create + Confirm Automatic CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateMultiUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + req_data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 7000, + true, + "automatic", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Refund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 7000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SyncRefund"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); +}); + +context("Card - Full Refund flow test for 3DS", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + afterEach("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context("Card - Partial Refund flow test for 3DS", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 1200, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context("Fully Refund Card-ThreeDS payment flow test Create+Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context( + "Partially Refund Card-ThreeDS payment flow test Create+Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 3000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, +); + +context("Card - Full Refund for fully captured 3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Capture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context("Card - Partial Refund for fully captured 3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Capture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 5000, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 1500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context("Card - Full Refund for partially captured 3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); + +context("Card - partial Refund for partially captured 3DS payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("Confirm 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PartialCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 50, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00009-SyncRefund.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00009-SyncRefund.cy.js new file mode 100644 index 00000000000..0f14dad72d6 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00009-SyncRefund.cy.js @@ -0,0 +1,89 @@ +import confirmBody from "../../fixtures/confirm-body.json"; +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import refundBody from "../../fixtures/refund-flow-body.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - Sync Refund flow test", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "Refund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.refundCallTest(refundBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("sync-refund-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SyncRefund" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.syncRefundCallTest(req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00010-CreateSingleuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00010-CreateSingleuseMandate.cy.js new file mode 100644 index 00000000000..00faf6dfcba --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00010-CreateSingleuseMandate.cy.js @@ -0,0 +1,199 @@ +import captureBody from "../../fixtures/capture-flow-body.json"; +import citConfirmBody from "../../fixtures/create-mandate-cit.json"; +import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - SingleUse Mandates flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context( + "Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateSingleUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 7000, + true, + "automatic", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + }, + ); + + context( + "Card - NoThreeDS Create + Confirm Manual CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateSingleUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 6500, + true, + "manual", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("cit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 6500, + true, + "manual", + globalState, + ); + }); + + it("mit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("list-mandate-call-test", () => { + cy.listMandateCallTest(globalState); + }); + }, + ); + + context( + "Card - ThreeDS Create + Confirm Manual CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateSingleUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 6500, + true, + "manual", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("cit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + + it("list-mandate-call-test", () => { + cy.listMandateCallTest(globalState); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00011-CreateMultiuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00011-CreateMultiuseMandate.cy.js new file mode 100644 index 00000000000..1dee7ea901f --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00011-CreateMultiuseMandate.cy.js @@ -0,0 +1,222 @@ +import captureBody from "../../fixtures/capture-flow-body.json"; +import citConfirmBody from "../../fixtures/create-mandate-cit.json"; +import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - MultiUse Mandates flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context( + "Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateMultiUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 7000, + true, + "automatic", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + }, + ); + + context( + "Card - NoThreeDS Create + Confirm Manual CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateMultiUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 6500, + true, + "manual", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("cit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT 1", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 6500, + true, + "manual", + globalState, + ); + }); + + it("mit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT 2", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 6500, + true, + "manual", + globalState, + ); + }); + + it("mit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context( + "Card - ThreeDS Create + Confirm Manual CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateMultiUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 6500, + true, + "manual", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("cit-capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 6500, + true, + "automatic", + globalState, + ); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00012-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00012-ListAndRevokeMandate.cy.js new file mode 100644 index 00000000000..28ffacb829c --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00012-ListAndRevokeMandate.cy.js @@ -0,0 +1,77 @@ +import citConfirmBody from "../../fixtures/create-mandate-cit.json"; +import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +import State from "../../utils/State"; + +let globalState; + +describe("Card - SingleUse Mandates flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context( + "Card - NoThreeDS Create + Confirm Automatic CIT and MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MandateSingleUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 7000, + true, + "automatic", + "new_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + + it("list-mandate-call-test", () => { + cy.listMandateCallTest(globalState); + }); + + it("revoke-mandate-call-test", () => { + cy.revokeMandateCallTest(globalState); + }); + + it("revoke-revoked-mandate-call-test", () => { + cy.revokeMandateCallTest(globalState); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js new file mode 100644 index 00000000000..c31a24e3931 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js @@ -0,0 +1,278 @@ +import captureBody from "../../fixtures/capture-flow-body.json"; +import confirmBody from "../../fixtures/confirm-body.json"; +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; +import customerCreateBody from "../../fixtures/create-customer-body.json"; +import SaveCardConfirmBody from "../../fixtures/save-card-confirm-body.json"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; +import State from "../../utils/State"; +let globalState; + +describe("Card - SaveCard payment flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + context( + "Save card for NoThreeDS automatic capture payment- Create+Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("customer-create-call-test", () => { + cy.createCustomerCallTest(customerCreateBody, globalState); + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("retrieve-customerPM-call-test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-save-card-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.saveCardConfirmCallTest( + SaveCardConfirmBody, + req_data, + res_data, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context( + "Save card for NoThreeDS manual full capture payment- Create+Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("customer-create-call-test", () => { + cy.createCustomerCallTest(customerCreateBody, globalState); + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("retrieve-customerPM-call-test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-save-card-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.saveCardConfirmCallTest( + SaveCardConfirmBody, + req_data, + res_data, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); + + context( + "Save card for NoThreeDS manual partial capture payment- Create + Confirm", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("customer-create-call-test", () => { + cy.createCustomerCallTest(customerCreateBody, globalState); + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("retrieve-customerPM-call-test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-save-card-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.saveCardConfirmCallTest( + SaveCardConfirmBody, + req_data, + res_data, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js new file mode 100644 index 00000000000..d90d86d8c41 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js @@ -0,0 +1,113 @@ +import citConfirmBody from "../../fixtures/create-mandate-cit.json"; +import mitConfirmBody from "../../fixtures/create-mandate-mit.json"; +import State from "../../utils/State"; +import getConnectorDetails from "../PaymentUtils/utils"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - SingleUse Mandates flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context( + "Card - NoThreeDS Create + Confirm Automatic CIT and Single use MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["ZeroAuthMandate"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 0, + true, + "automatic", + "setup_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + }, + ); + context( + "Card - NoThreeDS Create + Confirm Automatic CIT and Multi use MIT payment flow test", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Confirm No 3DS CIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["ZeroAuthMandate"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.citForMandatesCallTest( + citConfirmBody, + req_data, + res_data, + 0, + true, + "automatic", + "setup_mandate", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + it("Confirm No 3DS MIT", () => { + cy.mitForMandatesCallTest( + mitConfirmBody, + 7000, + true, + "automatic", + globalState, + ); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00015-ThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00015-ThreeDSManualCapture.cy.js new file mode 100644 index 00000000000..0aa4ad10492 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00015-ThreeDSManualCapture.cy.js @@ -0,0 +1,272 @@ +import createPaymentBody from "../../fixtures/create-payment-body.json"; +import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json"; +import confirmBody from "../../fixtures/confirm-body.json"; +import getConnectorDetails from "../PaymentUtils/utils"; +import State from "../../utils/State"; +import captureBody from "../../fixtures/capture-flow-body.json"; +import * as utils from "../PaymentUtils/utils"; + +let globalState; + +describe("Card - ThreeDS Manual payment flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + afterEach("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context("Card - ThreeDS Manual Full Capture payment flow test", () => { + context("payment Create and Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest(confirmBody, req_data, res_data, true, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + + context("Payment Create+Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = createConfirmPaymentBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Capture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 6500, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + }); + + context( + "Card - ThreeDS Manual Partial Capture payment flow test - Create and Confirm", + () => { + context("payment Create and Payment Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + createPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it("confirm-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + confirmBody, + req_data, + res_data, + true, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = confirmBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + + context("payment + Confirm", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("create+confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["3DSManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPaymentTest( + createConfirmPaymentBody, + req_data, + res_data, + "three_ds", + "manual", + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Handle redirection", () => { + let expected_redirection = createConfirmPaymentBody["return_url"]; + cy.handleRedirection(globalState, expected_redirection); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("capture-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PartialCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.captureCallTest(captureBody, req_data, res_data, 100, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + }); + }, + ); +}); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00016-BankTransfers.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00016-BankTransfers.cy.js similarity index 93% rename from cypress-tests/cypress/e2e/ConnectorTest/00016-BankTransfers.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00016-BankTransfers.cy.js index da4fab34b8e..6e132f5a1b6 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00016-BankTransfers.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00016-BankTransfers.cy.js @@ -1,7 +1,7 @@ import confirmBody from "../../fixtures/confirm-body.json"; import createPaymentBody from "../../fixtures/create-payment-body.json"; import State from "../../utils/State"; -import getConnectorDetails, * as utils from "../ConnectorUtils/utils"; +import getConnectorDetails, * as utils from "../PaymentUtils/utils"; let globalState; @@ -37,7 +37,7 @@ describe("Bank Transfers", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -58,7 +58,7 @@ describe("Bank Transfers", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -70,7 +70,7 @@ describe("Bank Transfers", () => { cy.handleBankTransferRedirection( globalState, payment_method_type, - expected_redirection + expected_redirection, ); }); }); diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00017-BankRedirect.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js similarity index 95% rename from cypress-tests/cypress/e2e/ConnectorTest/00017-BankRedirect.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js index 3a636b2020a..0706cf15b13 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00017-BankRedirect.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js @@ -1,7 +1,7 @@ import confirmBody from "../../fixtures/confirm-body.json"; import createPaymentBody from "../../fixtures/create-payment-body.json"; import State from "../../utils/State"; -import getConnectorDetails, * as utils from "../ConnectorUtils/utils"; +import getConnectorDetails, * as utils from "../PaymentUtils/utils"; let globalState; @@ -41,7 +41,7 @@ describe("Bank Redirect tests", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -62,7 +62,7 @@ describe("Bank Redirect tests", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -89,7 +89,7 @@ describe("Bank Redirect tests", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -110,7 +110,7 @@ describe("Bank Redirect tests", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -123,7 +123,7 @@ describe("Bank Redirect tests", () => { cy.handleBankRedirectRedirection( globalState, payment_method_type, - expected_redirection + expected_redirection, ); }); }); @@ -149,7 +149,7 @@ describe("Bank Redirect tests", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -170,7 +170,7 @@ describe("Bank Redirect tests", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -183,7 +183,7 @@ describe("Bank Redirect tests", () => { cy.handleBankRedirectRedirection( globalState, payment_method_type, - expected_redirection + expected_redirection, ); }); }); @@ -208,7 +208,7 @@ describe("Bank Redirect tests", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -229,7 +229,7 @@ describe("Bank Redirect tests", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -242,7 +242,7 @@ describe("Bank Redirect tests", () => { cy.handleBankRedirectRedirection( globalState, payment_method_type, - expected_redirection + expected_redirection, ); }); }); @@ -267,7 +267,7 @@ describe("Bank Redirect tests", () => { res_data, "three_ds", "automatic", - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -288,7 +288,7 @@ describe("Bank Redirect tests", () => { req_data, res_data, true, - globalState + globalState, ); if (should_continue) should_continue = utils.should_continue_further(res_data); @@ -301,7 +301,7 @@ describe("Bank Redirect tests", () => { cy.handleBankRedirectRedirection( globalState, payment_method_type, - expected_redirection + expected_redirection, ); }); }); diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js similarity index 100% rename from cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js rename to cypress-tests/cypress/e2e/PaymentUtils/Adyen.js diff --git a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js new file mode 100644 index 00000000000..a34190c2092 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js @@ -0,0 +1,369 @@ +const successfulNo3DSCardDetails = { + card_number: "4242424242424242", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4000000000001091", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + amount: 6500, + amount_capturable: 0, + amount_received: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "partially_captured", + amount: 6500, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js new file mode 100644 index 00000000000..0969e4088dd --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js @@ -0,0 +1,414 @@ +const successfulNo3DSCardDetails = { + card_number: "4242424242424242", + card_exp_month: "10", + card_exp_year: "30", + card_holder_name: "John", + card_cvc: "737", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4000000000001091", + card_exp_month: "10", + card_exp_year: "30", + card_holder_name: "Joseph", + card_cvc: "737", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + amount: 6500, + amount_capturable: 0, + amount_received: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "partially_captured", + amount: 6500, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by bluesnap", + }, + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Bluesnap is not implemented", + code: "IR_00", + }, + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Commons.js b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js similarity index 100% rename from cypress-tests/cypress/e2e/ConnectorUtils/Commons.js rename to cypress-tests/cypress/e2e/PaymentUtils/Commons.js diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js new file mode 100644 index 00000000000..d4818ce2941 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js @@ -0,0 +1,370 @@ +const successfulNo3DSCardDetails = { + card_number: "4242424242424242", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4000000000001091", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + amount: 6500, + amount_capturable: 0, + amount_received: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "partially_captured", + amount: 6500, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js new file mode 100644 index 00000000000..c420bb88445 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js @@ -0,0 +1,417 @@ +const successfulNo3DSCardDetails = { + card_number: "4000000000002503", + card_exp_month: "08", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "999", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4000000000002503", + card_exp_month: "10", + card_exp_year: "25", + card_holder_name: "morino", + card_cvc: "999", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "processing", + amount: 6500, + amount_capturable: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "processing", + amount: 6500, + amount_capturable: 6500, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 400, + body: { + error: { + code: "IR_16", + message: + "You cannot cancel this payment because it has status processing", + type: "invalid_request", + }, + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by nmi", + }, + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Nmi is not implemented", + code: "IR_00", + }, + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js new file mode 100644 index 00000000000..69c39f0dc8b --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js @@ -0,0 +1,429 @@ +const successfulNo3DSCardDetails = { + card_number: "4012000033330026", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4868719460707704", + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "processing", + amount: 6500, + amount_capturable: 6500, + amount_received: 0, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "processing", + amount: 6500, + amount_capturable: 6500, + amount_received: 0, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "HE_03", + reason: "debit mandate payment is not supported by paypal", + }, + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Paypal is not implemented", + code: "IR_00", + }, + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js new file mode 100644 index 00000000000..841c40b8736 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js @@ -0,0 +1,373 @@ +const successfulTestCard = "4242424242424242"; +const successful3DSCard = "4000002760003184"; + +const successfulNo3DSCardDetails = { + card_number: "4242424242424242", + card_exp_month: "10", + card_exp_year: "25", + card_holder_name: "morino", + card_cvc: "737", +}; + +const successfulThreeDSTestCardDetails = { + card_number: "4000002760003184", + card_exp_month: "10", + card_exp_year: "25", + card_holder_name: "morino", + card_cvc: "737", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + }, + }, + }, + "3DSManualCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + "3DSAutoCapture": { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + No3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + No3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + Capture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + amount: 6500, + amount_capturable: 0, + amount_received: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "partially_captured", + amount: 6500, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + PartialRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SyncRefund: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + card: successfulThreeDSTestCardDetails, + currency: "USD", + mandate_type: { + multi_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + ZeroAuthMandate: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + mandate_type: { + single_use: { + amount: 8000, + currency: "USD", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + card: successfulNo3DSCardDetails, + currency: "USD", + 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", + }, + }, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js b/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js similarity index 100% rename from cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js rename to cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/utils.js b/cypress-tests/cypress/e2e/PaymentUtils/utils.js similarity index 100% rename from cypress-tests/cypress/e2e/ConnectorUtils/utils.js rename to cypress-tests/cypress/e2e/PaymentUtils/utils.js diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00000-AccountCreate.cy.js b/cypress-tests/cypress/e2e/PayoutTest/00000-AccountCreate.cy.js similarity index 83% rename from cypress-tests/cypress/e2e/ConnectorTest/00000-AccountCreate.cy.js rename to cypress-tests/cypress/e2e/PayoutTest/00000-AccountCreate.cy.js index aed901c2997..c1b62c883fa 100644 --- a/cypress-tests/cypress/e2e/ConnectorTest/00000-AccountCreate.cy.js +++ b/cypress-tests/cypress/e2e/PayoutTest/00000-AccountCreate.cy.js @@ -4,16 +4,14 @@ import State from "../../utils/State"; let globalState; describe("Account Create flow test", () => { - before("seed global state", () => { - - cy.task('getGlobalState').then((state) => { + cy.task("getGlobalState").then((state) => { globalState = new State(state); - }) - }) + }); + }); after("flush global state", () => { - cy.task('setGlobalState', globalState.data); - }) + cy.task("setGlobalState", globalState.data); + }); it("merchant-create-call-test", () => { cy.merchantCreateCallTest(merchantCreateBody, globalState); @@ -21,5 +19,4 @@ describe("Account Create flow test", () => { it("api-key-create-call-test", () => { cy.apiKeyCreateTest(apiKeyCreateBody, globalState); }); - }); diff --git a/cypress-tests/cypress/e2e/PayoutTest/00001-CustomerCreate.cy.js b/cypress-tests/cypress/e2e/PayoutTest/00001-CustomerCreate.cy.js new file mode 100644 index 00000000000..584296bdaee --- /dev/null +++ b/cypress-tests/cypress/e2e/PayoutTest/00001-CustomerCreate.cy.js @@ -0,0 +1,18 @@ +import customerCreateBody from "../../fixtures/create-customer-body.json"; +import State from "../../utils/State"; + +let globalState; + +describe("Customer Create flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + it("customer-create-call-test", () => { + cy.createCustomerCallTest(customerCreateBody, globalState); + }); +}); diff --git a/cypress-tests/cypress/e2e/PayoutTest/00002-ConnectorCreate.cy.js b/cypress-tests/cypress/e2e/PayoutTest/00002-ConnectorCreate.cy.js new file mode 100644 index 00000000000..16292914aa2 --- /dev/null +++ b/cypress-tests/cypress/e2e/PayoutTest/00002-ConnectorCreate.cy.js @@ -0,0 +1,21 @@ +import createConnectorBody from "../../fixtures/create-connector-body.json"; +import State from "../../utils/State"; + +let globalState; +describe("Connector Account Create flow test", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + console.log("seeding globalState -> " + JSON.stringify(globalState)); + }); + }); + + after("flush global state", () => { + console.log("flushing globalState -> " + JSON.stringify(globalState)); + cy.task("setGlobalState", globalState.data); + }); + + it("connector-create-call-test", () => { + cy.createPayoutConnectorCallTest(createConnectorBody, globalState); + }); +}); diff --git a/cypress-tests/cypress/e2e/PayoutTest/00003-CardTest.cy.js b/cypress-tests/cypress/e2e/PayoutTest/00003-CardTest.cy.js new file mode 100644 index 00000000000..4f563a689ce --- /dev/null +++ b/cypress-tests/cypress/e2e/PayoutTest/00003-CardTest.cy.js @@ -0,0 +1,140 @@ +import createPayoutBody from "../../fixtures/create-payout-confirm-body.json"; +import State from "../../utils/State"; +import * as utils from "../PayoutUtils/utils"; + +let globalState; + +describe("Card - Auto Fulfill", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + console.log("seeding globalState -> " + JSON.stringify(globalState)); + cy.task( + "cli_log", + "SEEDING GLOBAL STATE -> " + JSON.stringify(globalState), + ); + }); + }); + + afterEach("flush global state", () => { + console.log("flushing globalState -> " + JSON.stringify(globalState)); + cy.task("setGlobalState", globalState.data); + cy.task( + "cli_log", + " FLUSHING GLOBAL STATE -> " + JSON.stringify(globalState), + ); + }); + + context("Payout Card with Auto Fulfill", () => { + it("confirm-payout-call-with-auto-fulfill-test", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Fulfill"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPayoutTest( + createPayoutBody, + req_data, + res_data, + true, + true, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payout-call-test", () => { + cy.retrievePayoutCallTest(globalState); + }); + }); + + context("Payout Card with Manual Fulfill - Create Confirm", () => { + it("confirm-payout-call-with-manual-fulfill-test", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Confirm"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPayoutTest( + createPayoutBody, + req_data, + res_data, + true, + false, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("fulfill-payout-call-test", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Fulfill"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.fulfillPayoutCallTest({}, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payout-call-test", () => { + cy.retrievePayoutCallTest(globalState); + }); + }); + + context("Payout Card with Manual Fulfill - Create Intent + Confirm", () => { + it("create-payout-call", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Create"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createConfirmPayoutTest( + createPayoutBody, + req_data, + res_data, + false, + false, + globalState, + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-payout-call", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Confirm"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.updatePayoutCallTest({}, req_data, res_data, false, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("fulfill-payout-call-test", () => { + let data = utils.getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Fulfill"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.fulfillPayoutCallTest({}, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payout-call-test", () => { + cy.retrievePayoutCallTest(globalState); + }); + }); +}); diff --git a/cypress-tests/cypress/e2e/PayoutUtils/Adyen.js b/cypress-tests/cypress/e2e/PayoutUtils/Adyen.js new file mode 100644 index 00000000000..eaa25e7fa29 --- /dev/null +++ b/cypress-tests/cypress/e2e/PayoutUtils/Adyen.js @@ -0,0 +1,59 @@ +const card_data = { + card_number: "4111111111111111", + expiry_month: "3", + expiry_year: "2030", + card_holder_name: "John Smith", +}; + +export const connectorDetails = { + card_pm: { + Create: { + Request: { + payout_method_data: { + card: card_data, + }, + currency: "EUR", + payout_type: "card", + }, + Response: { + status: 200, + body: { + status: "requires_creation", + payout_type: "card", + }, + }, + }, + Confirm: { + Request: { + payout_method_data: { + card: card_data, + }, + currency: "EUR", + payout_type: "card", + }, + Response: { + status: 200, + body: { + status: "requires_fulfillment", + payout_type: "card", + }, + }, + }, + Fulfill: { + Request: { + payout_method_data: { + card: card_data, + }, + currency: "EUR", + payout_type: "card", + }, + Response: { + status: 200, + body: { + status: "success", + payout_type: "card", + }, + }, + }, + }, +}; diff --git a/cypress-tests/cypress/e2e/PayoutUtils/utils.js b/cypress-tests/cypress/e2e/PayoutUtils/utils.js new file mode 100644 index 00000000000..619fd313f20 --- /dev/null +++ b/cypress-tests/cypress/e2e/PayoutUtils/utils.js @@ -0,0 +1,33 @@ +import { connectorDetails as adyenConnectorDetails } from "./Adyen.js"; + +const connectorDetails = { + adyen: adyenConnectorDetails, +}; + +export const getConnectorDetails = (connectorId) => { + let x = getValueByKey(connectorDetails, connectorId); + return x; +}; + +function getValueByKey(jsonObject, key) { + const data = + typeof jsonObject === "string" ? JSON.parse(jsonObject) : jsonObject; + + if (data && typeof data === "object" && key in data) { + return data[key]; + } else { + return null; + } +} + +export const should_continue_further = (res_data) => { + if ( + res_data.body.error !== undefined || + res_data.body.error_code !== undefined || + res_data.body.error_message !== undefined + ) { + return false; + } else { + return true; + } +}; diff --git a/cypress-tests/cypress/fixtures/create-payout-confirm-body.json b/cypress-tests/cypress/fixtures/create-payout-confirm-body.json new file mode 100644 index 00000000000..2eb32bf26da --- /dev/null +++ b/cypress-tests/cypress/fixtures/create-payout-confirm-body.json @@ -0,0 +1,36 @@ +{ + "amount": 1, + "currency": "EUR", + "customer_id": "payout_customer", + "email": "[email protected]", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "Its my first payout request", + "payout_type": "card", + "payout_method_data": {}, + "billing": { + "address": { + "line1": "1467", + "line2": "Harrison Street", + "line3": "Harrison Street", + "city": "San Fransico", + "state": "NY", + "zip": "94122", + "country": "US", + "first_name": "John", + "last_name": "Doe" + }, + "phone": { + "number": "8056594427", + "country_code": "+91" + } + }, + "entity_type": "Individual", + "recurring": false, + "metadata": { + "ref": "123" + }, + "auto_fulfill": true, + "confirm": true +} diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index 4842ed01734..59a20166868 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -30,9 +30,9 @@ import { handleRedirection } from "./redirectionHandler"; function logRequestId(xRequestId) { if (xRequestId) { - cy.task('cli_log', "x-request-id -> " + xRequestId); + cy.task("cli_log", "x-request-id -> " + xRequestId); } else { - cy.task('cli_log', "x-request-id is not available in the response headers"); + cy.task("cli_log", "x-request-id is not available in the response headers"); } } @@ -43,27 +43,30 @@ function defaultErrorHandler(response, response_data) { } } -Cypress.Commands.add("merchantCreateCallTest", (merchantCreateBody, globalState) => { - const randomMerchantId = RequestBodyUtils.generateRandomString(); - RequestBodyUtils.setMerchantId(merchantCreateBody, randomMerchantId); - globalState.set("merchantId", randomMerchantId); +Cypress.Commands.add( + "merchantCreateCallTest", + (merchantCreateBody, globalState) => { + const randomMerchantId = RequestBodyUtils.generateRandomString(); + RequestBodyUtils.setMerchantId(merchantCreateBody, randomMerchantId); + globalState.set("merchantId", randomMerchantId); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/accounts`, - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "api-key": globalState.get("adminApiKey"), - }, - body: merchantCreateBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/accounts`, + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "api-key": globalState.get("adminApiKey"), + }, + body: merchantCreateBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); - // Handle the response as needed - globalState.set("publishableKey", response.body.publishable_key); - }); -}); + // Handle the response as needed + globalState.set("publishableKey", response.body.publishable_key); + }); + }, +); Cypress.Commands.add("apiKeyCreateTest", (apiKeyCreateBody, globalState) => { cy.request({ @@ -76,113 +79,191 @@ Cypress.Commands.add("apiKeyCreateTest", (apiKeyCreateBody, globalState) => { }, body: apiKeyCreateBody, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); // Handle the response as needed globalState.set("apiKey", response.body.api_key); }); }); -Cypress.Commands.add("createConnectorCallTest", (createConnectorBody, globalState) => { - const merchantId = globalState.get("merchantId"); - createConnectorBody.connector_name = globalState.get("connectorId"); - // readFile is used to read the contents of the file and it always returns a promise ([Object Object]) due to its asynchronous nature - // it is best to use then() to handle the response within the same block of code - cy.readFile(globalState.get("connectorAuthFilePath")).then((jsonContent) => { - const authDetails = getValueByKey(JSON.stringify(jsonContent), globalState.get("connectorId")); - createConnectorBody.connector_account_details = authDetails; - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/account/${merchantId}/connectors`, - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "api-key": globalState.get("adminApiKey"), +Cypress.Commands.add( + "createConnectorCallTest", + (createConnectorBody, globalState) => { + const merchantId = globalState.get("merchantId"); + createConnectorBody.connector_name = globalState.get("connectorId"); + // readFile is used to read the contents of the file and it always returns a promise ([Object Object]) due to its asynchronous nature + // it is best to use then() to handle the response within the same block of code + cy.readFile(globalState.get("connectorAuthFilePath")).then( + (jsonContent) => { + const authDetails = getValueByKey( + JSON.stringify(jsonContent), + globalState.get("connectorId"), + ); + createConnectorBody.connector_account_details = authDetails; + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/account/${merchantId}/connectors`, + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "api-key": globalState.get("adminApiKey"), + }, + body: createConnectorBody, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + if (response.status === 200) { + expect(globalState.get("connectorId")).to.equal( + response.body.connector_name, + ); + } else { + cy.task( + "cli_log", + "response status -> " + JSON.stringify(response.status), + ); + } + }); }, - body: createConnectorBody, - failOnStatusCode: false - }).then((response) => { - logRequestId(response.headers['x-request-id']); + ); + }, +); - if (response.status === 200) { - expect(globalState.get("connectorId")).to.equal(response.body.connector_name); - } else { - cy.task('cli_log', "response status -> " + JSON.stringify(response.status)); - } - }); - }); -}); +Cypress.Commands.add( + "createPayoutConnectorCallTest", + (createConnectorBody, globalState) => { + const merchantId = globalState.get("merchantId"); + let connectorName = globalState.get("connectorId"); + createConnectorBody.connector_name = connectorName; + createConnectorBody.connector_type = "payout_processor"; + // readFile is used to read the contents of the file and it always returns a promise ([Object Object]) due to its asynchronous nature + // it is best to use then() to handle the response within the same block of code + cy.readFile(globalState.get("connectorAuthFilePath")).then( + (jsonContent) => { + const authDetails = getValueByKey( + JSON.stringify(jsonContent), + `${connectorName}_payout`, + ); + createConnectorBody.connector_account_details = authDetails; + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/account/${merchantId}/connectors`, + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "api-key": globalState.get("adminApiKey"), + }, + body: createConnectorBody, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + if (response.status === 200) { + expect(globalState.get("connectorId")).to.equal( + response.body.connector_name, + ); + } else { + cy.task( + "cli_log", + "response status -> " + JSON.stringify(response.status), + ); + } + }); + }, + ); + }, +); function getValueByKey(jsonObject, key) { - const data = typeof jsonObject === 'string' ? JSON.parse(jsonObject) : jsonObject; - if (data && typeof data === 'object' && key in data) { + const data = + typeof jsonObject === "string" ? JSON.parse(jsonObject) : jsonObject; + if (data && typeof data === "object" && key in data) { return data[key]; } else { return null; } } -Cypress.Commands.add("createCustomerCallTest", (customerCreateBody, globalState) => { - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/customers`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - body: customerCreateBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); +Cypress.Commands.add( + "createCustomerCallTest", + (customerCreateBody, globalState) => { + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/customers`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + body: customerCreateBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); - globalState.set("customerId", response.body.customer_id); - }); -}); + globalState.set("customerId", response.body.customer_id); + }); + }, +); -Cypress.Commands.add("createPaymentIntentTest", (request, req_data, res_data, authentication_type, capture_method, globalState) => { - if (!request || typeof request !== "object" || !req_data.currency || !authentication_type) { - throw new Error("Invalid parameters provided to createPaymentIntentTest command"); - } - request.currency = req_data.currency; - request.authentication_type = authentication_type; - request.capture_method = capture_method; - request.setup_future_usage = req_data.setup_future_usage; - request.customer_acceptance = req_data.customer_acceptance; - request.customer_id = globalState.get("customerId"); - globalState.set("paymentAmount", request.amount); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments`, - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: request, - }).then((response) => { - logRequestId(response.headers['x-request-id']); +Cypress.Commands.add( + "createPaymentIntentTest", + ( + request, + req_data, + res_data, + authentication_type, + capture_method, + globalState, + ) => { + if ( + !request || + typeof request !== "object" || + !req_data.currency || + !authentication_type + ) { + throw new Error( + "Invalid parameters provided to createPaymentIntentTest command", + ); + } + request.currency = req_data.currency; + request.authentication_type = authentication_type; + request.capture_method = capture_method; + request.setup_future_usage = req_data.setup_future_usage; + request.customer_acceptance = req_data.customer_acceptance; + request.customer_id = globalState.get("customerId"); + globalState.set("paymentAmount", request.amount); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments`, + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: request, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - - if(response.status === 200){ - expect(response.body).to.have.property("client_secret"); - const clientSecret = response.body.client_secret; - globalState.set("clientSecret", clientSecret); - globalState.set("paymentID", response.body.payment_id); - cy.log(clientSecret); - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + expect(response.body).to.have.property("client_secret"); + const clientSecret = response.body.client_secret; + globalState.set("clientSecret", clientSecret); + globalState.set("paymentID", response.body.payment_id); + cy.log(clientSecret); + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + expect(request.amount).to.equal(response.body.amount); + expect(null).to.equal(response.body.amount_received); + expect(request.amount).to.equal(response.body.amount_capturable); + } else { + defaultErrorHandler(response, res_data); } - expect(request.amount).to.equal(response.body.amount); - expect(null).to.equal(response.body.amount_received); - expect(request.amount).to.equal(response.body.amount_capturable); - } - else { - defaultErrorHandler(response, res_data); - } - }); -}); + }); + }, +); Cypress.Commands.add("paymentMethodsCallTest", (globalState) => { const clientSecret = globalState.get("clientSecret"); @@ -196,7 +277,7 @@ Cypress.Commands.add("paymentMethodsCallTest", (globalState) => { "api-key": globalState.get("publishableKey"), }, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); expect(response.body).to.have.property("redirect_url"); @@ -206,60 +287,69 @@ Cypress.Commands.add("paymentMethodsCallTest", (globalState) => { }); }); -Cypress.Commands.add("confirmCallTest", (confirmBody, req_data, res_data, confirm, globalState) => { - const paymentIntentID = globalState.get("paymentID"); - confirmBody.payment_method_data.card = req_data.card; - confirmBody.confirm = confirm; - confirmBody.client_secret = globalState.get("clientSecret"); - confirmBody.customer_acceptance = req_data.customer_acceptance; +Cypress.Commands.add( + "confirmCallTest", + (confirmBody, req_data, res_data, confirm, globalState) => { + const paymentIntentID = globalState.get("paymentID"); + confirmBody.payment_method_data.card = req_data.card; + confirmBody.confirm = confirm; + confirmBody.client_secret = globalState.get("clientSecret"); + confirmBody.customer_acceptance = req_data.customer_acceptance; - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("publishableKey"), - }, - failOnStatusCode: false, - body: confirmBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - if(response.status === 200){ - globalState.set("paymentID", paymentIntentID); - if (response.body.capture_method === "automatic") { - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url"); - globalState.set("nextActionUrl", response.body.next_action.redirect_to_url); - } else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("publishableKey"), + }, + failOnStatusCode: false, + body: confirmBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + globalState.set("paymentID", paymentIntentID); + if (response.body.capture_method === "automatic") { + if (response.body.authentication_type === "three_ds") { + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + globalState.set( + "nextActionUrl", + response.body.next_action.redirect_to_url, + ); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, res_data); } - } else { - defaultErrorHandler(response, res_data); - } - } else if (response.body.capture_method === "manual") { - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url") - globalState.set("nextActionUrl", response.body.next_action.redirect_to_url); - } - else if (response.body.authentication_type === "no_three_ds") { - for (const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + } else if (response.body.capture_method === "manual") { + if (response.body.authentication_type === "three_ds") { + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + globalState.set( + "nextActionUrl", + response.body.next_action.redirect_to_url, + ); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, res_data); } - } else { - defaultErrorHandler(response, res_data); } + } else { + defaultErrorHandler(response, res_data); } - } - else { - defaultErrorHandler(response, res_data); - } - }); -}); + }); + }, +); Cypress.Commands.add( "confirmBankRedirectCallTest", @@ -294,8 +384,12 @@ Cypress.Commands.add( response.body.capture_method === "automatic" || response.body.capture_method === "manual" ) { - if (response.body.status !== "failed") { // we get many statuses here, hence this verification - if (connectorId === "adyen" && response.body.payment_method_type === "blik") { + if (response.body.status !== "failed") { + // we get many statuses here, hence this verification + if ( + connectorId === "adyen" && + response.body.payment_method_type === "blik" + ) { expect(response.body) .to.have.property("next_action") .to.have.property("type") @@ -306,11 +400,13 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); globalState.set( "nextActionUrl", - response.body.next_action.redirect_to_url + response.body.next_action.redirect_to_url, ); } } else if (response.body.status === "failed") { - expect(response.body.error_code).to.equal(res_data.body.error_code); + expect(response.body.error_code).to.equal( + res_data.body.error_code, + ); } } else { defaultErrorHandler(response, res_data); @@ -326,7 +422,7 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); globalState.set( "nextActionUrl", - response.body.next_action.redirect_to_url + response.body.next_action.redirect_to_url, ); } else { defaultErrorHandler(response, res_data); @@ -336,7 +432,7 @@ Cypress.Commands.add( defaultErrorHandler(response, res_data); } }); - } + }, ); Cypress.Commands.add( @@ -349,7 +445,7 @@ Cypress.Commands.add( confirmBody.confirm = confirm; confirmBody.client_secret = globalState.get("clientSecret"); globalState.set("paymentMethodType", confirmBody.payment_method_type); - + cy.request({ method: "POST", url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, @@ -376,7 +472,7 @@ Cypress.Commands.add( .to.have.property("qr_code_url"); globalState.set( "nextActionUrl", // This is intentionally kept as nextActionUrl to avoid issues during handleRedirection call, - response.body.next_action.qr_code_url + response.body.next_action.qr_code_url, ); break; default: @@ -385,7 +481,7 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); globalState.set( "nextActionUrl", - response.body.next_action.redirect_to_url + response.body.next_action.redirect_to_url, ); break; } @@ -396,190 +492,214 @@ Cypress.Commands.add( defaultErrorHandler(response, res_data); } }); - } + }, ); -Cypress.Commands.add("createConfirmPaymentTest", (createConfirmPaymentBody, req_data, res_data, authentication_type, capture_method, globalState) => { - createConfirmPaymentBody.payment_method_data.card = req_data.card; - createConfirmPaymentBody.authentication_type = authentication_type; - createConfirmPaymentBody.currency = req_data.currency; - createConfirmPaymentBody.capture_method = capture_method; - createConfirmPaymentBody.customer_acceptance = req_data.customer_acceptance; - createConfirmPaymentBody.setup_future_usage = req_data.setup_future_usage; - createConfirmPaymentBody.customer_id = globalState.get("customerId"); - - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: createConfirmPaymentBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); - - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - - if(response.status === 200){ - if (response.body.capture_method === "automatic") { - expect(response.body).to.have.property("status"); - globalState.set("paymentAmount", createConfirmPaymentBody.amount); - globalState.set("paymentID", response.body.payment_id); - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url") - globalState.set("nextActionUrl", response.body.next_action.redirect_to_url); - } - else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); - } - } else { - defaultErrorHandler(response, res_data); - } - } - else if (response.body.capture_method === "manual") { - expect(response.body).to.have.property("status"); - globalState.set("paymentAmount", createConfirmPaymentBody.amount); - globalState.set("paymentID", response.body.payment_id); - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url") - globalState.set("nextActionUrl", response.body.next_action.redirect_to_url); - } - else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); - } - } else { - defaultErrorHandler(response, res_data); - } - } - } - else{ - defaultErrorHandler(response, res_data); - } - }); -}); +Cypress.Commands.add( + "createConfirmPaymentTest", + ( + createConfirmPaymentBody, + req_data, + res_data, + authentication_type, + capture_method, + globalState, + ) => { + createConfirmPaymentBody.payment_method_data.card = req_data.card; + createConfirmPaymentBody.authentication_type = authentication_type; + createConfirmPaymentBody.currency = req_data.currency; + createConfirmPaymentBody.capture_method = capture_method; + createConfirmPaymentBody.customer_acceptance = req_data.customer_acceptance; + createConfirmPaymentBody.setup_future_usage = req_data.setup_future_usage; + createConfirmPaymentBody.customer_id = globalState.get("customerId"); -// This is consequent saved card payment confirm call test(Using payment token) -Cypress.Commands.add("saveCardConfirmCallTest", (saveCardConfirmBody, req_data, res_data,globalState) => { - const paymentIntentID = globalState.get("paymentID"); - saveCardConfirmBody.card_cvc = req_data.card.card_cvc; - saveCardConfirmBody.payment_token = globalState.get("paymentToken"); - saveCardConfirmBody.client_secret = globalState.get("clientSecret"); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("publishableKey"), - }, - failOnStatusCode: false, - body: saveCardConfirmBody, - }) - .then((response) => { - logRequestId(response.headers['x-request-id']); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: createConfirmPaymentBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); expect(res_data.status).to.equal(response.status); expect(response.headers["content-type"]).to.include("application/json"); - globalState.set("paymentID", paymentIntentID); - if(response.status === 200){ + + if (response.status === 200) { if (response.body.capture_method === "automatic") { + expect(response.body).to.have.property("status"); + globalState.set("paymentAmount", createConfirmPaymentBody.amount); + globalState.set("paymentID", response.body.payment_id); if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") + expect(response.body) + .to.have.property("next_action") .to.have.property("redirect_to_url"); - const nextActionUrl = response.body.next_action.redirect_to_url; - } else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + globalState.set( + "nextActionUrl", + response.body.next_action.redirect_to_url, + ); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); } - expect(response.body.customer_id).to.equal(globalState.get("customerId")); } else { - // Handle other authentication types as needed defaultErrorHandler(response, res_data); } } else if (response.body.capture_method === "manual") { + expect(response.body).to.have.property("status"); + globalState.set("paymentAmount", createConfirmPaymentBody.amount); + globalState.set("paymentID", response.body.payment_id); if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url") + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + globalState.set( + "nextActionUrl", + response.body.next_action.redirect_to_url, + ); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, res_data); } - else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { + } + } else { + defaultErrorHandler(response, res_data); + } + }); + }, +); + +// This is consequent saved card payment confirm call test(Using payment token) +Cypress.Commands.add( + "saveCardConfirmCallTest", + (saveCardConfirmBody, req_data, res_data, globalState) => { + const paymentIntentID = globalState.get("paymentID"); + saveCardConfirmBody.card_cvc = req_data.card.card_cvc; + saveCardConfirmBody.payment_token = globalState.get("paymentToken"); + saveCardConfirmBody.client_secret = globalState.get("clientSecret"); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("publishableKey"), + }, + failOnStatusCode: false, + body: saveCardConfirmBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + globalState.set("paymentID", paymentIntentID); + if (response.status === 200) { + if (response.body.capture_method === "automatic") { + if (response.body.authentication_type === "three_ds") { + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + const nextActionUrl = response.body.next_action.redirect_to_url; + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { expect(res_data.body[key]).to.equal(response.body[key]); } - expect(response.body.customer_id).to.equal(globalState.get("customerId")); + expect(response.body.customer_id).to.equal( + globalState.get("customerId"), + ); + } else { + // Handle other authentication types as needed + defaultErrorHandler(response, res_data); + } + } else if (response.body.capture_method === "manual") { + if (response.body.authentication_type === "three_ds") { + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + expect(response.body.customer_id).to.equal( + globalState.get("customerId"), + ); } else { // Handle other authentication types as needed defaultErrorHandler(response, res_data); } } - } - else { + } else { defaultErrorHandler(response, res_data); } }); -}); + }, +); -Cypress.Commands.add("captureCallTest", (requestBody, req_data, res_data, amount_to_capture, globalState) => { - const payment_id = globalState.get("paymentID"); - requestBody.amount_to_capture = amount_to_capture; - let amount = globalState.get("paymentAmount"); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments/${payment_id}/capture`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: requestBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); +Cypress.Commands.add( + "captureCallTest", + (requestBody, req_data, res_data, amount_to_capture, globalState) => { + const payment_id = globalState.get("paymentID"); + requestBody.amount_to_capture = amount_to_capture; + let amount = globalState.get("paymentAmount"); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments/${payment_id}/capture`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: requestBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - if(response.body.capture_method !== undefined) { - expect(response.body.payment_id).to.equal(payment_id); - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + if (response.body.capture_method !== undefined) { + expect(response.body.payment_id).to.equal(payment_id); + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, res_data); } - } - else{ - defaultErrorHandler(response, res_data); - } - }); -}); + }); + }, +); -Cypress.Commands.add("voidCallTest", (requestBody, req_data, res_data, globalState) => { - const payment_id = globalState.get("paymentID"); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments/${payment_id}/cancel`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: requestBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); +Cypress.Commands.add( + "voidCallTest", + (requestBody, req_data, res_data, globalState) => { + const payment_id = globalState.get("paymentID"); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments/${payment_id}/cancel`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: requestBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - if(response.status === 200) { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, res_data); } - } - else{ - defaultErrorHandler(response, res_data); - } - }); -}); + }); + }, +); Cypress.Commands.add("retrievePaymentCallTest", (globalState) => { const payment_id = globalState.get("paymentID"); @@ -592,7 +712,7 @@ Cypress.Commands.add("retrievePaymentCallTest", (globalState) => { }, failOnStatusCode: false, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); expect(response.body.payment_id).to.equal(payment_id); @@ -601,168 +721,189 @@ Cypress.Commands.add("retrievePaymentCallTest", (globalState) => { }); }); -Cypress.Commands.add("refundCallTest", (requestBody, req_data, res_data, refund_amount, globalState) => { - const payment_id = globalState.get("paymentID"); - requestBody.payment_id = payment_id; - requestBody.amount = refund_amount; - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/refunds`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: requestBody - }).then((response) => { - logRequestId(response.headers['x-request-id']); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - - if(response.status === 200) { - globalState.set("refundId", response.body.refund_id); - for(const key in res_data.body) { +Cypress.Commands.add( + "refundCallTest", + (requestBody, req_data, res_data, refund_amount, globalState) => { + const payment_id = globalState.get("paymentID"); + requestBody.payment_id = payment_id; + requestBody.amount = refund_amount; + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/refunds`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: requestBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + globalState.set("refundId", response.body.refund_id); + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + expect(response.body.payment_id).to.equal(payment_id); + } else { + defaultErrorHandler(response, res_data); + } + }); + }, +); + +Cypress.Commands.add( + "syncRefundCallTest", + (req_data, res_data, globalState) => { + const refundId = globalState.get("refundId"); + cy.request({ + method: "GET", + url: `${globalState.get("baseUrl")}/refunds/${refundId}`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + for (const key in res_data.body) { expect(res_data.body[key]).to.equal(response.body[key]); } - expect(response.body.payment_id).to.equal(payment_id); - } - else{ - defaultErrorHandler(response, res_data); - } - - }); -}); + }); + }, +); -Cypress.Commands.add("syncRefundCallTest", (req_data, res_data, globalState) => { - const refundId = globalState.get("refundId"); - cy.request({ - method: "GET", - url: `${globalState.get("baseUrl")}/refunds/${refundId}`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - }).then((response) => { - logRequestId(response.headers['x-request-id']); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); - } - }); -}); +Cypress.Commands.add( + "citForMandatesCallTest", + ( + requestBody, + req_data, + res_data, + amount, + confirm, + capture_method, + payment_type, + globalState, + ) => { + requestBody.payment_method_data.card = req_data.card; + requestBody.payment_type = payment_type; + requestBody.confirm = confirm; + requestBody.amount = amount; + requestBody.currency = req_data.currency; + requestBody.capture_method = capture_method; + requestBody.mandate_data.mandate_type = req_data.mandate_type; + requestBody.customer_id = globalState.get("customerId"); + globalState.set("paymentAmount", requestBody.amount); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: requestBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + globalState.set("mandateId", response.body.mandate_id); + globalState.set("paymentID", response.body.payment_id); -Cypress.Commands.add("citForMandatesCallTest", (requestBody, req_data, res_data, amount, confirm, capture_method, payment_type, globalState) => { - requestBody.payment_method_data.card = req_data.card; - requestBody.payment_type = payment_type; - requestBody.confirm = confirm; - requestBody.amount = amount; - requestBody.currency = req_data.currency; - requestBody.capture_method = capture_method; - requestBody.mandate_data.mandate_type = req_data.mandate_type; - requestBody.customer_id = globalState.get("customerId"); - globalState.set("paymentAmount", requestBody.amount); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: requestBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); - expect(res_data.status).to.equal(response.status); - expect(response.headers["content-type"]).to.include("application/json"); - globalState.set("mandateId", response.body.mandate_id); - globalState.set("paymentID", response.body.payment_id); + if (response.status === 200) { + if (response.body.capture_method === "automatic") { + expect(response.body).to.have.property("mandate_id"); + if (response.body.authentication_type === "three_ds") { + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + const nextActionUrl = response.body.next_action.redirect_to_url; + globalState.set( + "nextActionUrl", + response.body.next_action.redirect_to_url, + ); + cy.log(response.body); + cy.log(nextActionUrl); + } else if (response.body.authentication_type === "no_three_ds") { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else if (response.body.capture_method === "manual") { + expect(response.body).to.have.property("mandate_id"); + if (response.body.authentication_type === "three_ds") { + expect(response.body).to.have.property("next_action"); + } + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } + } else { + defaultErrorHandler(response, res_data); + } + }); + }, +); - if(response.status === 200) { +Cypress.Commands.add( + "mitForMandatesCallTest", + (requestBody, amount, confirm, capture_method, globalState) => { + requestBody.amount = amount; + requestBody.confirm = confirm; + requestBody.capture_method = capture_method; + requestBody.mandate_id = globalState.get("mandateId"); + requestBody.customer_id = globalState.get("customerId"); + globalState.set("paymentAmount", requestBody.amount); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: requestBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(response.headers["content-type"]).to.include("application/json"); + globalState.set("paymentID", response.body.payment_id); if (response.body.capture_method === "automatic") { - expect(response.body).to.have.property("mandate_id"); if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") + expect(response.body) + .to.have.property("next_action") .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; - globalState.set("nextActionUrl", response.body.next_action.redirect_to_url); cy.log(response.body); cy.log(nextActionUrl); } else if (response.body.authentication_type === "no_three_ds") { - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); - } - } - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + expect(response.body.status).to.equal("succeeded"); + } else { + defaultErrorHandler(response, res_data); } - } - else if (response.body.capture_method === "manual") { - expect(response.body).to.have.property("mandate_id"); + } else if (response.body.capture_method === "manual") { if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - } - for(const key in res_data.body) { - expect(res_data.body[key]).to.equal(response.body[key]); + expect(response.body) + .to.have.property("next_action") + .to.have.property("redirect_to_url"); + const nextActionUrl = response.body.next_action.redirect_to_url; + cy.log(response.body); + cy.log(nextActionUrl); + } else if (response.body.authentication_type === "no_three_ds") { + expect(response.body.status).to.equal("requires_capture"); + } else { + defaultErrorHandler(response, res_data); } } - } - else{ - defaultErrorHandler(response, res_data); - } - }); -}); - -Cypress.Commands.add("mitForMandatesCallTest", (requestBody, amount, confirm, capture_method, globalState) => { - requestBody.amount = amount; - requestBody.confirm = confirm; - requestBody.capture_method = capture_method; - requestBody.mandate_id = globalState.get("mandateId"); - requestBody.customer_id = globalState.get("customerId"); - globalState.set("paymentAmount", requestBody.amount); - cy.request({ - method: "POST", - url: `${globalState.get("baseUrl")}/payments`, - headers: { - "Content-Type": "application/json", - "api-key": globalState.get("apiKey"), - }, - failOnStatusCode: false, - body: requestBody, - }).then((response) => { - logRequestId(response.headers['x-request-id']); - expect(response.headers["content-type"]).to.include("application/json"); - globalState.set("paymentID", response.body.payment_id); - if (response.body.capture_method === "automatic") { - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url"); - const nextActionUrl = response.body.next_action.redirect_to_url; - cy.log(response.body); - cy.log(nextActionUrl); - } else if (response.body.authentication_type === "no_three_ds") { - expect(response.body.status).to.equal("succeeded"); - } else { - defaultErrorHandler(response, res_data); - } - } - else if (response.body.capture_method === "manual") { - if (response.body.authentication_type === "three_ds") { - expect(response.body).to.have.property("next_action") - .to.have.property("redirect_to_url"); - const nextActionUrl = response.body.next_action.redirect_to_url; - cy.log(response.body); - cy.log(nextActionUrl); - } else if (response.body.authentication_type === "no_three_ds") { - expect(response.body.status).to.equal("requires_capture"); - } else { - defaultErrorHandler(response, res_data); - } - } - }); -}); - + }); + }, +); Cypress.Commands.add("listMandateCallTest", (globalState) => { const customerId = globalState.get("customerId"); @@ -774,7 +915,7 @@ Cypress.Commands.add("listMandateCallTest", (globalState) => { "api-key": globalState.get("apiKey"), }, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); @@ -783,7 +924,7 @@ Cypress.Commands.add("listMandateCallTest", (globalState) => { if (response.body[i].mandate_id === globalState.get("mandateId")) { expect(response.body[i].status).to.equal("active"); } - }; + } }); }); @@ -796,9 +937,9 @@ Cypress.Commands.add("revokeMandateCallTest", (globalState) => { "Content-Type": "application/json", "api-key": globalState.get("apiKey"), }, - failOnStatusCode: false + failOnStatusCode: false, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); if (response.body.status === 200) { @@ -809,17 +950,20 @@ Cypress.Commands.add("revokeMandateCallTest", (globalState) => { }); }); -Cypress.Commands.add("handleRedirection", (globalState, expected_redirection) => { - let connectorId = globalState.get("connectorId"); - let expected_url = new URL(expected_redirection); - let redirection_url = new URL(globalState.get("nextActionUrl")); - handleRedirection( - "three_ds", - { redirection_url, expected_url }, - connectorId, - null - ); -}); +Cypress.Commands.add( + "handleRedirection", + (globalState, expected_redirection) => { + let connectorId = globalState.get("connectorId"); + let expected_url = new URL(expected_redirection); + let redirection_url = new URL(globalState.get("nextActionUrl")); + handleRedirection( + "three_ds", + { redirection_url, expected_url }, + connectorId, + null, + ); + }, +); Cypress.Commands.add( "handleBankRedirectRedirection", @@ -834,10 +978,10 @@ Cypress.Commands.add( "bank_redirect", { redirection_url, expected_url }, connectorId, - payment_method_type + payment_method_type, ); } - } + }, ); Cypress.Commands.add( @@ -850,9 +994,9 @@ Cypress.Commands.add( "bank_transfer", { redirection_url, expected_redirection }, connectorId, - payment_method_type + payment_method_type, ); - } + }, ); Cypress.Commands.add("listCustomerPMCallTest", (globalState) => { @@ -865,15 +1009,15 @@ Cypress.Commands.add("listCustomerPMCallTest", (globalState) => { "api-key": globalState.get("apiKey"), }, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); if (response.body.customer_payment_methods[0]?.payment_token) { - const paymentToken = response.body.customer_payment_methods[0].payment_token; + const paymentToken = + response.body.customer_payment_methods[0].payment_token; globalState.set("paymentToken", paymentToken); // Set paymentToken in globalState expect(paymentToken).to.equal(globalState.get("paymentToken")); // Verify paymentToken - } - else { + } else { defaultErrorHandler(response, res_data); } }); @@ -889,8 +1033,144 @@ Cypress.Commands.add("listRefundCallTest", (requestBody, globalState) => { }, body: requestBody, }).then((response) => { - logRequestId(response.headers['x-request-id']); + logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); - expect(response.body.data).to.be.an('array').and.not.empty; + expect(response.body.data).to.be.an("array").and.not.empty; + }); +}); + +Cypress.Commands.add( + "createConfirmPayoutTest", + ( + createConfirmPayoutBody, + req_data, + res_data, + confirm, + auto_fulfill, + globalState, + ) => { + for (const key in req_data) { + createConfirmPayoutBody[key] = req_data[key]; + } + createConfirmPayoutBody.auto_fulfill = auto_fulfill; + createConfirmPayoutBody.confirm = confirm; + createConfirmPayoutBody.customer_id = globalState.get("customerId"); + + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payouts/create`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: createConfirmPayoutBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + globalState.set("payoutAmount", createConfirmPayoutBody.amount); + globalState.set("payoutID", response.body.payout_id); + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + expect(response.body).to.have.property("error"); + for (const key in res_data.body.error) { + expect(res_data.body.error[key]).to.equal(response.body.error[key]); + } + } + }); + }, +); + +Cypress.Commands.add( + "fulfillPayoutCallTest", + (payoutFulfillBody, req_data, res_data, globalState) => { + payoutFulfillBody.payout_id = globalState.get("payoutID"); + + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payouts/${globalState.get("payoutID")}/fulfill`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: payoutFulfillBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + expect(response.body).to.have.property("error"); + for (const key in res_data.body.error) { + expect(res_data.body.error[key]).to.equal(response.body.error[key]); + } + } + }); + }, +); + +Cypress.Commands.add( + "updatePayoutCallTest", + (payoutConfirmBody, req_data, res_data, auto_fulfill, globalState) => { + payoutConfirmBody.confirm = true; + payoutConfirmBody.auto_fulfill = auto_fulfill; + + cy.request({ + method: "PUT", + url: `${globalState.get("baseUrl")}/payouts/${globalState.get("payoutID")}`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + body: payoutConfirmBody, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + expect(res_data.status).to.equal(response.status); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + for (const key in res_data.body) { + expect(res_data.body[key]).to.equal(response.body[key]); + } + } else { + expect(response.body).to.have.property("error"); + for (const key in res_data.body.error) { + expect(res_data.body.error[key]).to.equal(response.body.error[key]); + } + } }); + }, +); + +Cypress.Commands.add("retrievePayoutCallTest", (globalState) => { + const payout_id = globalState.get("payoutID"); + cy.request({ + method: "GET", + url: `${globalState.get("baseUrl")}/payouts/${payout_id}`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + + expect(response.headers["content-type"]).to.include("application/json"); + expect(response.body.payout_id).to.equal(payout_id); + expect(response.body.amount).to.equal(globalState.get("payoutAmount")); }); +}); diff --git a/cypress-tests/cypress/support/e2e.js b/cypress-tests/cypress/support/e2e.js index 9b1ef71ce0f..3a252243880 100644 --- a/cypress-tests/cypress/support/e2e.js +++ b/cypress-tests/cypress/support/e2e.js @@ -14,7 +14,7 @@ // *********************************************************** // Import commands.js using ES2015 syntax: -import './commands'; +import "./commands"; // Alternatively you can use CommonJS syntax: -// require('./commands') \ No newline at end of file +// require('./commands') diff --git a/cypress-tests/cypress/support/redirectionhandler.js b/cypress-tests/cypress/support/redirectionhandler.js index 6e481858153..f6b65d82514 100644 --- a/cypress-tests/cypress/support/redirectionhandler.js +++ b/cypress-tests/cypress/support/redirectionhandler.js @@ -4,7 +4,7 @@ export function handleRedirection( redirection_type, urls, connectorId, - payment_method_type + payment_method_type, ) { switch (redirection_type) { case "three_ds": @@ -15,7 +15,7 @@ export function handleRedirection( urls.redirection_url, urls.expected_url, connectorId, - payment_method_type + payment_method_type, ); break; case "bank_transfer": @@ -23,7 +23,7 @@ export function handleRedirection( urls.redirection_url, urls.expected_url, connectorId, - payment_method_type + payment_method_type, ); break; default: @@ -35,7 +35,7 @@ function bankTransferRedirection( redirection_url, expected_url, connectorId, - payment_method_type + payment_method_type, ) { cy.request(redirection_url.href).then((response) => { switch (connectorId) { @@ -119,7 +119,7 @@ function bankRedirectRedirection( redirection_url, expected_url, connectorId, - payment_method_type + payment_method_type, ) { let verifyUrl = false; cy.visit(redirection_url.href); @@ -136,7 +136,7 @@ function bankRedirectRedirection( case "ideal": cy.get(":nth-child(4) > td > p").should( "contain.text", - "Your Payment was Authorised/Refused/Cancelled (It may take up to five minutes to show on the Payment List)" + "Your Payment was Authorised/Refused/Cancelled (It may take up to five minutes to show on the Payment List)", ); cy.get(".btnLink").click(); cy.url().should("include", "status=succeeded"); @@ -144,12 +144,12 @@ function bankRedirectRedirection( break; case "giropay": cy.get( - ".rds-cookies-overlay__allow-all-cookies-btn > .rds-button" + ".rds-cookies-overlay__allow-all-cookies-btn > .rds-button", ).click(); cy.wait(5000); cy.get(".normal-3").should( "contain.text", - "Bank suchen ‑ mit giropay zahlen." + "Bank suchen ‑ mit giropay zahlen.", ); cy.get("#bankSearch").type("giropay TestBank{enter}"); cy.get(".normal-2 > div").click(); @@ -186,14 +186,14 @@ function bankRedirectRedirection( .should("contain", "Continue") .click(); } - } + }, ); break; case "trustly": break; default: throw new Error( - `Unsupported payment method type: ${payment_method_type}` + `Unsupported payment method type: ${payment_method_type}`, ); } verifyUrl = true; @@ -203,16 +203,16 @@ function bankRedirectRedirection( case "eps": cy.get("._transactionId__header__iXVd_").should( "contain.text", - "Bank suchen ‑ mit eps zahlen." + "Bank suchen ‑ mit eps zahlen.", ); cy.get(".BankSearch_searchInput__uX_9l").type( - "Allgemeine Sparkasse Oberösterreich Bank AG{enter}" + "Allgemeine Sparkasse Oberösterreich Bank AG{enter}", ); cy.get(".BankSearch_searchResultItem__lbcKm").click(); cy.get("._transactionId__primaryButton__nCa0r").click(); cy.get("#loginTitle").should( "contain.text", - "eps Online-Überweisung Login" + "eps Online-Überweisung Login", ); cy.get("#user") .should("be.visible") @@ -224,7 +224,7 @@ function bankRedirectRedirection( case "ideal": cy.get("p").should( "contain.text", - "Choose your iDeal Issuer Bank please" + "Choose your iDeal Issuer Bank please", ); cy.get("#issuerSearchInput").click(); cy.get("#issuerSearchInput").type("ING{enter}"); @@ -233,10 +233,10 @@ function bankRedirectRedirection( case "giropay": cy.get("._transactionId__header__iXVd_").should( "contain.text", - "Bank suchen ‑ mit giropay zahlen." + "Bank suchen ‑ mit giropay zahlen.", ); cy.get(".BankSearch_searchInput__uX_9l").type( - "Volksbank Hildesheim{enter}" + "Volksbank Hildesheim{enter}", ); cy.get(".BankSearch_searchIcon__EcVO7").click(); cy.get(".BankSearch_bankWrapper__R5fUK").click(); @@ -249,7 +249,7 @@ function bankRedirectRedirection( break; default: throw new Error( - `Unsupported payment method type: ${payment_method_type}` + `Unsupported payment method type: ${payment_method_type}`, ); } verifyUrl = false; @@ -273,7 +273,7 @@ function verifyReturnUrl(redirection_url, expected_url, forward_flow) { { args: { expected_url: expected_url.origin } }, ({ expected_url }) => { cy.window().its("location.origin").should("eq", expected_url); - } + }, ); } } @@ -303,7 +303,7 @@ async function fetchAndParseQRCode(url) { const qrCodeData = jsQR( imageData.data, imageData.width, - imageData.height + imageData.height, ); if (qrCodeData) { diff --git a/cypress-tests/cypress/utils/State.js b/cypress-tests/cypress/utils/State.js index dae4963000f..b7b96dae5ee 100644 --- a/cypress-tests/cypress/utils/State.js +++ b/cypress-tests/cypress/utils/State.js @@ -5,7 +5,9 @@ class State { this.data["connectorId"] = Cypress.env("CONNECTOR"); this.data["baseUrl"] = Cypress.env("BASEURL"); this.data["adminApiKey"] = Cypress.env("ADMINAPIKEY"); - this.data["connectorAuthFilePath"] = Cypress.env("CONNECTOR_AUTH_FILE_PATH"); + this.data["connectorAuthFilePath"] = Cypress.env( + "CONNECTOR_AUTH_FILE_PATH", + ); } set(key, val) { diff --git a/cypress-tests/package.json b/cypress-tests/package.json index af4b0244fbd..b6602ece459 100644 --- a/cypress-tests/package.json +++ b/cypress-tests/package.json @@ -6,7 +6,9 @@ "scripts": { "cypress": "npx cypress open", "cypress-e2e": "npx cypress run --e2e", - "cypress:ci": "npx cypress run --headless" + "cypress:ci": "npx cypress run --headless", + "cypress:payments": "cypress run --spec 'cypress/e2e/PaymentTest/**/*'", + "cypress:payouts": "cypress run --spec 'cypress/e2e/PayoutTest/**/*'" }, "author": "", "license": "ISC", diff --git a/cypress-tests/readme.md b/cypress-tests/readme.md index 511625cdbfb..78251ef9c81 100644 --- a/cypress-tests/readme.md +++ b/cypress-tests/readme.md @@ -141,7 +141,7 @@ Cypress.Commands.add("listMandateCallTest", (globalState) => { } else { cy.task( "cli_log", - "x-request-id is not available in the response headers" + "x-request-id is not available in the response headers", ); } expect(response.headers["content-type"]).to.include("application/json");
feat
Add service level testing for Payouts (#4744)
bf2352b14ae7d7343474424be0f0a4b0fee1b0f2
2023-05-13 14:58:35
Nishant Joshi
feat(error): add feature-gated stacktrace to error received from API (#1104)
false
diff --git a/Cargo.lock b/Cargo.lock index 100e28daaf4..6cb3e124104 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1782,6 +1782,7 @@ checksum = "5f00447f331c7f726db5b8532ebc9163519eed03c6d7c8b73c90b3ff5646ac85" dependencies = [ "anyhow", "rustc_version", + "serde", ] [[package]] diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index c11e9cebde6..7d52c2c7297 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -12,6 +12,7 @@ errors = [ ] multiple_mca = [] dummy_connector = [] +detailed_errors = [] [dependencies] actix-web = { version = "4.3.1", optional = true } diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rs index d67ab177739..365be676f16 100644 --- a/crates/api_models/src/errors/types.rs +++ b/crates/api_models/src/errors/types.rs @@ -15,6 +15,8 @@ pub struct ApiError { pub error_identifier: u16, pub error_message: String, pub extra: Option<Extra>, + #[cfg(feature = "detailed_errors")] + pub stacktrace: Option<serde_json::Value>, } impl ApiError { @@ -29,6 +31,8 @@ impl ApiError { error_identifier, error_message: error_message.to_string(), extra, + #[cfg(feature = "detailed_errors")] + stacktrace: None, } } } @@ -41,6 +45,9 @@ struct ErrorResponse<'a> { code: String, #[serde(flatten)] extra: &'a Option<Extra>, + #[cfg(feature = "detailed_errors")] + #[serde(skip_serializing_if = "Option::is_none")] + stacktrace: Option<&'a serde_json::Value>, } impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> { @@ -52,6 +59,9 @@ impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> { message: Cow::Borrowed(value.get_internal_error().error_message.as_str()), error_type, extra: &error_info.extra, + + #[cfg(feature = "detailed_errors")] + stacktrace: error_info.stacktrace.as_ref(), } } } @@ -114,6 +124,23 @@ impl ApiErrorResponse { } } + pub fn get_internal_error_mut(&mut self) -> &mut ApiError { + match self { + Self::Unauthorized(i) + | Self::ForbiddenCommonResource(i) + | Self::ForbiddenPrivateResource(i) + | Self::Conflict(i) + | Self::Gone(i) + | Self::Unprocessable(i) + | Self::InternalServerError(i) + | Self::NotImplemented(i) + | Self::NotFound(i) + | Self::MethodNotAllowed(i) + | Self::BadRequest(i) + | Self::ConnectorError(i, _) => i, + } + } + pub(crate) fn error_type(&self) -> &'static str { match self { Self::Unauthorized(_) diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 88fcf92d38b..97fdd0b7fa9 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -26,6 +26,7 @@ vergen = ["router_env/vergen"] multiple_mca = ["api_models/multiple_mca"] dummy_connector = ["api_models/dummy_connector"] external_access_dc = ["dummy_connector"] +detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] [dependencies] diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 78c5c551719..91d95e8a8fc 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -609,3 +609,5 @@ impl common_utils::errors::ErrorSwitch<StripeErrorCode> for errors::ApiErrorResp self.clone().into() } } + +impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 05246d3bdc6..87985e71f57 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -8,7 +8,7 @@ use serde::Serialize; use crate::{ core::errors::{self, RouterResult}, routes::app::AppStateInfo, - services::{api, authentication as auth, logger}, + services::{self, api, authentication as auth, logger}, }; #[instrument(skip(request, payload, state, func, api_authentication))] @@ -25,6 +25,7 @@ where Q: Serialize + std::fmt::Debug + 'a, S: TryFrom<Q> + Serialize, E: Serialize + error_stack::Context + actix_web::ResponseError + Clone, + error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug, A: AppStateInfo, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index eb06a09400c..356580a5207 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -461,3 +461,47 @@ pub enum WebhooksFlowError { #[error("Dispute webhook status validation failed")] DisputeWebhookValidationFailed, } + +#[cfg(feature = "detailed_errors")] +pub mod error_stack_parsing { + + #[derive(serde::Deserialize)] + pub struct NestedErrorStack<'a> { + context: std::borrow::Cow<'a, str>, + attachments: Vec<std::borrow::Cow<'a, str>>, + sources: Vec<NestedErrorStack<'a>>, + } + + #[derive(serde::Serialize, Debug)] + struct LinearErrorStack<'a> { + context: std::borrow::Cow<'a, str>, + #[serde(skip_serializing_if = "Vec::is_empty")] + attachments: Vec<std::borrow::Cow<'a, str>>, + } + + #[derive(serde::Serialize, Debug)] + pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>); + + impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> { + fn from(value: Vec<NestedErrorStack<'a>>) -> Self { + let multi_layered_errors: Vec<_> = value + .into_iter() + .flat_map(|current_error| { + [LinearErrorStack { + context: current_error.context, + attachments: current_error.attachments, + }] + .into_iter() + .chain( + Into::<VecLinearErrorStack<'a>>::into(current_error.sources) + .0 + .into_iter(), + ) + }) + .collect(); + Self(multi_layered_errors) + } + } +} +#[cfg(feature = "detailed_errors")] +pub use error_stack_parsing::*; diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 523e55f228f..3af3580baac 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -300,6 +300,8 @@ impl actix_web::ResponseError for ApiErrorResponse { } } +impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {} + impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index fb61feeedfb..ca0e860284f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -630,9 +630,45 @@ where pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse where T: actix_web::ResponseError + error_stack::Context + Clone, + Report<T>: EmbedError, { logger::error!(?error); - HttpResponse::from_error(error.current_context().clone()) + HttpResponse::from_error(error.embed().current_context().clone()) +} + +pub trait EmbedError: Sized { + fn embed(self) -> Self { + self + } +} + +impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> { + fn embed(self) -> Self { + #[cfg(feature = "detailed_errors")] + { + let mut report = self; + let error_trace = serde_json::to_value(&report).ok().and_then(|inner| { + serde_json::from_value::<Vec<errors::NestedErrorStack<'_>>>(inner) + .ok() + .map(Into::<errors::VecLinearErrorStack<'_>>::into) + .map(serde_json::to_value) + .transpose() + .ok() + .flatten() + }); + + match report.downcast_mut::<api_models::errors::types::ApiErrorResponse>() { + None => {} + Some(inner) => { + inner.get_internal_error_mut().stacktrace = error_trace; + } + } + report + } + + #[cfg(not(feature = "detailed_errors"))] + self + } } pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
feat
add feature-gated stacktrace to error received from API (#1104)
b1cb053a55e9ce4d78f7770b53e39700311d9cd4
2024-06-06 14:00:09
Sanchith Hegde
refactor(webhooks): extract incoming and outgoing webhooks into separate modules (#4870)
false
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 22560777705..a209d90f316 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -1,2387 +1,16 @@ +mod incoming; +mod outgoing; pub mod types; pub mod utils; #[cfg(feature = "olap")] pub mod webhook_events; -use std::{str::FromStr, time::Instant}; - -use actix_web::FromRequest; -#[cfg(feature = "payouts")] -use api_models::payouts as payout_models; -use api_models::{ - payments::HeaderPayload, - webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, - webhooks::{self, WebhookResponseTracker}, -}; -use common_utils::{ - errors::ReportSwitchExt, events::ApiEventsType, ext_traits::Encode, request::RequestContent, -}; -use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, Mask, PeekInterface, Secret}; -use router_env::{ - instrument, - tracing::{self, Instrument}, - tracing_actix_web::RequestId, -}; - -#[cfg(feature = "payouts")] -use super::payouts; -use super::{errors::StorageErrorExt, metrics}; -#[cfg(feature = "stripe")] -use crate::compatibility::stripe::webhooks as stripe_webhooks; -#[cfg(not(feature = "payouts"))] -use crate::routes::SessionState; -use crate::{ - consts, - core::{ - api_locking, - errors::{self, ConnectorErrorExt, CustomResult, RouterResponse}, - payments, refunds, +pub(crate) use self::{ + incoming::incoming_webhooks_wrapper, + outgoing::{ + create_event_and_trigger_outgoing_webhook, get_outgoing_webhook_request, + trigger_webhook_and_raise_event, }, - db::StorageInterface, - events::{ - api_logs::ApiEvent, - outgoing_webhook_logs::{OutgoingWebhookEvent, OutgoingWebhookEventMetric}, - }, - logger, - routes::{ - app::{ReqState, SessionStateInfo}, - lock_utils, - metrics::request::add_attributes, - }, - services::{self, authentication as auth}, - types::{ - api::{self, mandates::MandateResponseExt}, - domain::{self, types as domain_types}, - storage::{self, enums}, - transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, - }, - utils::{self as helper_utils, generate_id, OptionExt, ValueExt}, - workflows::outgoing_webhook_retry, }; -#[cfg(feature = "payouts")] -use crate::{routes::SessionState, types::storage::PayoutAttemptUpdate}; -const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; const MERCHANT_ID: &str = "merchant_id"; - -pub async fn payments_incoming_webhook_flow( - state: SessionState, - req_state: ReqState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - source_verified: bool, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - let consume_or_trigger_flow = if source_verified { - payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) - } else { - payments::CallConnectorAction::Trigger - }; - let payments_response = match webhook_details.object_reference_id { - webhooks::ObjectReferenceId::PaymentId(id) => { - let payment_id = get_payment_id( - state.store.as_ref(), - &id, - merchant_account.merchant_id.as_str(), - merchant_account.storage_scheme, - ) - .await?; - - let lock_action = api_locking::LockAction::Hold { - input: api_locking::LockingInput { - unique_locking_key: payment_id, - api_identifier: lock_utils::ApiIdentifier::Payments, - override_lock_retries: None, - }, - }; - - lock_action - .clone() - .perform_locking_action(&state, merchant_account.merchant_id.to_string()) - .await?; - - let response = Box::pin(payments::payments_core::< - api::PSync, - api::PaymentsResponse, - _, - _, - _, - >( - state.clone(), - req_state, - merchant_account.clone(), - key_store.clone(), - payments::operations::PaymentStatus, - api::PaymentsRetrieveRequest { - resource_id: id, - merchant_id: Some(merchant_account.merchant_id.clone()), - force_sync: true, - connector: None, - param: None, - merchant_connector_details: None, - client_secret: None, - expand_attempts: None, - expand_captures: None, - }, - services::AuthFlow::Merchant, - consume_or_trigger_flow, - None, - HeaderPayload::default(), - )) - .await; - - lock_action - .free_lock_action(&state, merchant_account.merchant_id.to_owned()) - .await?; - - match response { - Ok(value) => value, - Err(err) - if matches!( - err.current_context(), - &errors::ApiErrorResponse::PaymentNotFound - ) && state - .conf - .webhooks - .ignore_error - .payment_not_found - .unwrap_or(true) => - { - metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( - &metrics::CONTEXT, - 1, - &[add_attributes( - "merchant_id", - merchant_account.merchant_id.clone(), - )], - ); - return Ok(WebhookResponseTracker::NoEffect); - } - error @ Err(_) => error?, - } - } - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( - "Did not get payment id as object reference id in webhook payments flow", - )?, - }; - - match payments_response { - services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { - let payment_id = payments_response - .payment_id - .clone() - .get_required_value("payment_id") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("payment id not received from payments core")?; - - let status = payments_response.status; - - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); - - // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook - if let Some(outgoing_event_type) = event_type { - let primary_object_created_at = payments_response.created; - create_event_and_trigger_outgoing_webhook( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Payments, - payment_id.clone(), - enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), - primary_object_created_at, - ) - .await?; - }; - - let response = WebhookResponseTracker::Payment { payment_id, status }; - - Ok(response) - } - - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received non-json response from payments core")?, - } -} - -#[cfg(feature = "payouts")] -pub async fn payouts_incoming_webhook_flow( - state: SessionState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - event_type: webhooks::IncomingWebhookEvent, - source_verified: bool, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); - if source_verified { - let db = &*state.store; - //find payout_attempt by object_reference_id - let payout_attempt = match webhook_details.object_reference_id { - webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type { - webhooks::PayoutIdType::PayoutAttemptId(id) => db - .find_payout_attempt_by_merchant_id_payout_attempt_id( - &merchant_account.merchant_id, - &id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout attempt")?, - webhooks::PayoutIdType::ConnectorPayoutId(id) => db - .find_payout_attempt_by_merchant_id_connector_payout_id( - &merchant_account.merchant_id, - &id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout attempt")?, - }, - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received a non-payout id when processing payout webhooks")?, - }; - - let payouts = db - .find_payout_by_merchant_id_payout_id( - &merchant_account.merchant_id, - &payout_attempt.payout_id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout")?; - - let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate { - connector_payout_id: payout_attempt.connector_payout_id.clone(), - status: common_enums::PayoutStatus::foreign_try_from(event_type) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("failed payout status mapping from event type")?, - error_message: None, - error_code: None, - is_eligible: payout_attempt.is_eligible, - }; - - let action_req = - payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest { - payout_id: payouts.payout_id.clone(), - }); - - let payout_data = - payouts::make_payout_data(&state, &merchant_account, &key_store, &action_req).await?; - - let updated_payout_attempt = db - .update_payout_attempt( - &payout_attempt, - payout_attempt_update, - &payout_data.payouts, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable_lazy(|| { - format!( - "Failed while updating payout attempt: payout_attempt_id: {}", - payout_attempt.payout_attempt_id - ) - })?; - - let event_type: Option<enums::EventType> = updated_payout_attempt.status.foreign_into(); - - // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook - if let Some(outgoing_event_type) = event_type { - let router_response = - payouts::response_handler(&merchant_account, &payout_data).await?; - - let payout_create_response: payout_models::PayoutCreateResponse = match router_response - { - services::ApplicationResponse::Json(response) => response, - _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout create response")?, - }; - - create_event_and_trigger_outgoing_webhook( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Payouts, - updated_payout_attempt.payout_id.clone(), - enums::EventObjectType::PayoutDetails, - api::OutgoingWebhookContent::PayoutDetails(payout_create_response), - Some(updated_payout_attempt.created_at), - ) - .await?; - } - - Ok(WebhookResponseTracker::Payout { - payout_id: updated_payout_attempt.payout_id, - status: updated_payout_attempt.status, - }) - } else { - metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - } -} - -#[instrument(skip_all)] -#[allow(clippy::too_many_arguments)] -pub async fn refunds_incoming_webhook_flow( - state: SessionState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - connector_name: &str, - source_verified: bool, - event_type: webhooks::IncomingWebhookEvent, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - let db = &*state.store; - //find refund by connector refund id - let refund = match webhook_details.object_reference_id { - webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { - webhooks::RefundIdType::RefundId(id) => db - .find_refund_by_merchant_id_refund_id( - &merchant_account.merchant_id, - &id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the refund")?, - webhooks::RefundIdType::ConnectorRefundId(id) => db - .find_refund_by_merchant_id_connector_refund_id_connector( - &merchant_account.merchant_id, - &id, - connector_name, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the refund")?, - }, - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received a non-refund id when processing refund webhooks")?, - }; - let refund_id = refund.refund_id.to_owned(); - //if source verified then update refund status else trigger refund sync - let updated_refund = if source_verified { - let refund_update = storage::RefundUpdate::StatusUpdate { - connector_refund_id: None, - sent_to_gateway: true, - refund_status: common_enums::RefundStatus::foreign_try_from(event_type) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("failed refund status mapping from event type")?, - updated_by: merchant_account.storage_scheme.to_string(), - }; - db.update_refund( - refund.to_owned(), - refund_update, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? - } else { - Box::pin(refunds::refund_retrieve_core( - state.clone(), - merchant_account.clone(), - key_store.clone(), - api_models::refunds::RefundsRetrieveRequest { - refund_id: refund_id.to_owned(), - force_sync: Some(true), - merchant_connector_details: None, - }, - )) - .await - .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? - }; - let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into(); - - // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook - 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( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Refunds, - refund_id, - enums::EventObjectType::RefundDetails, - api::OutgoingWebhookContent::RefundDetails(refund_response), - Some(updated_refund.created_at), - ) - .await?; - } - - Ok(WebhookResponseTracker::Refund { - payment_id: updated_refund.payment_id, - refund_id: updated_refund.refund_id, - status: updated_refund.refund_status, - }) -} - -pub async fn get_payment_attempt_from_object_reference_id( - state: &SessionState, - object_reference_id: webhooks::ObjectReferenceId, - merchant_account: &domain::MerchantAccount, -) -> CustomResult< - hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, - errors::ApiErrorResponse, -> { - let db = &*state.store; - match object_reference_id { - api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db - .find_payment_attempt_by_merchant_id_connector_txn_id( - &merchant_account.merchant_id, - id, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), - api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db - .find_payment_attempt_by_attempt_id_merchant_id( - id, - &merchant_account.merchant_id, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), - api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db - .find_payment_attempt_by_preprocessing_id_merchant_id( - id, - &merchant_account.merchant_id, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received a non-payment id for retrieving payment")?, - } -} - -#[allow(clippy::too_many_arguments)] -pub async fn get_or_update_dispute_object( - state: SessionState, - option_dispute: Option<diesel_models::dispute::Dispute>, - dispute_details: api::disputes::DisputePayload, - merchant_id: &str, - payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, - event_type: webhooks::IncomingWebhookEvent, - business_profile: &diesel_models::business_profile::BusinessProfile, - connector_name: &str, -) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { - let db = &*state.store; - match option_dispute { - None => { - metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); - let dispute_id = generate_id(consts::ID_LENGTH, "dp"); - let new_dispute = diesel_models::dispute::DisputeNew { - dispute_id, - amount: dispute_details.amount.clone(), - currency: dispute_details.currency, - dispute_stage: dispute_details.dispute_stage, - dispute_status: common_enums::DisputeStatus::foreign_try_from(event_type) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("event type to dispute status mapping failed")?, - payment_id: payment_attempt.payment_id.to_owned(), - connector: connector_name.to_owned(), - attempt_id: payment_attempt.attempt_id.to_owned(), - merchant_id: merchant_id.to_owned(), - connector_status: dispute_details.connector_status, - connector_dispute_id: dispute_details.connector_dispute_id, - connector_reason: dispute_details.connector_reason, - connector_reason_code: dispute_details.connector_reason_code, - challenge_required_by: dispute_details.challenge_required_by, - connector_created_at: dispute_details.created_at, - connector_updated_at: dispute_details.updated_at, - 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 - .insert_dispute(new_dispute.clone()) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) - } - Some(dispute) => { - logger::info!("Dispute Already exists, Updating the dispute details"); - metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); - let dispute_status = diesel_models::enums::DisputeStatus::foreign_try_from(event_type) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("event type to dispute state conversion failure")?; - crate::core::utils::validate_dispute_stage_and_dispute_status( - dispute.dispute_stage, - dispute.dispute_status, - dispute_details.dispute_stage, - dispute_status, - ) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("dispute stage and status validation failed")?; - let update_dispute = diesel_models::dispute::DisputeUpdate::Update { - dispute_stage: dispute_details.dispute_stage, - dispute_status, - connector_status: dispute_details.connector_status, - connector_reason: dispute_details.connector_reason, - connector_reason_code: dispute_details.connector_reason_code, - challenge_required_by: dispute_details.challenge_required_by, - connector_updated_at: dispute_details.updated_at, - }; - db.update_dispute(dispute, update_dispute) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) - } - } -} - -#[allow(clippy::too_many_arguments)] -pub async fn external_authentication_incoming_webhook_flow( - state: SessionState, - req_state: ReqState, - merchant_account: domain::MerchantAccount, - key_store: domain::MerchantKeyStore, - source_verified: bool, - event_type: webhooks::IncomingWebhookEvent, - request_details: &api::IncomingWebhookRequestDetails<'_>, - connector: &(dyn api::Connector + Sync), - object_ref_id: api::ObjectReferenceId, - business_profile: diesel_models::business_profile::BusinessProfile, - merchant_connector_account: domain::MerchantConnectorAccount, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - if source_verified { - let authentication_details = connector - .get_external_authentication_details(request_details) - .switch()?; - let trans_status = authentication_details.trans_status; - let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate { - authentication_status: common_enums::AuthenticationStatus::foreign_from( - trans_status.clone(), - ), - trans_status, - authentication_value: authentication_details.authentication_value, - eci: authentication_details.eci, - }; - let authentication = - if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) = - object_ref_id - { - match authentication_id_type { - webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state - .store - .find_authentication_by_merchant_id_authentication_id( - merchant_account.merchant_id.clone(), - authentication_id.clone(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { - id: authentication_id, - }) - .attach_printable("Error while fetching authentication record"), - webhooks::AuthenticationIdType::ConnectorAuthenticationId( - connector_authentication_id, - ) => state - .store - .find_authentication_by_merchant_id_connector_authentication_id( - merchant_account.merchant_id.clone(), - connector_authentication_id.clone(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { - id: connector_authentication_id, - }) - .attach_printable("Error while fetching authentication record"), - } - } else { - Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( - "received a non-external-authentication id for retrieving authentication", - ) - }?; - let updated_authentication = state - .store - .update_authentication_by_merchant_id_authentication_id( - authentication, - authentication_update, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while updating authentication")?; - // Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows - if let Some(payment_id) = updated_authentication.payment_id { - let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose())); - // Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook - if !is_pull_mechanism_enabled - && updated_authentication.authentication_type - == Some(common_enums::DecoupledAuthenticationType::Challenge) - && event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes - { - let payment_confirm_req = api::PaymentsRequest { - payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( - payment_id, - )), - merchant_id: Some(merchant_account.merchant_id.clone()), - ..Default::default() - }; - let payments_response = Box::pin(payments::payments_core::< - api::Authorize, - api::PaymentsResponse, - _, - _, - _, - >( - state.clone(), - req_state, - merchant_account.clone(), - key_store.clone(), - payments::PaymentConfirm, - payment_confirm_req, - services::api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - None, - HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), - )) - .await?; - match payments_response { - services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { - let payment_id = payments_response - .payment_id - .clone() - .get_required_value("payment_id") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("payment id not received from payments core")?; - let status = payments_response.status; - let event_type: Option<enums::EventType> = - payments_response.status.foreign_into(); - // Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client - let poll_id = super::utils::get_poll_id( - merchant_account.merchant_id.clone(), - super::utils::get_external_authentication_request_poll_id(&payment_id), - ); - let redis_conn = state - .store - .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get redis connection")?; - redis_conn - .set_key_without_modifying_ttl( - &poll_id, - api_models::poll::PollStatus::Completed.to_string(), - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add poll_id in redis")?; - // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook - if let Some(outgoing_event_type) = event_type { - let primary_object_created_at = payments_response.created; - create_event_and_trigger_outgoing_webhook( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Payments, - payment_id.clone(), - enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), - primary_object_created_at, - ) - .await?; - }; - let response = WebhookResponseTracker::Payment { payment_id, status }; - Ok(response) - } - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( - "Did not get payment id as object reference id in webhook payments flow", - )?, - } - } else { - Ok(WebhookResponseTracker::NoEffect) - } - } else { - Ok(WebhookResponseTracker::NoEffect) - } - } else { - logger::error!( - "Webhook source verification failed for external authentication webhook flow" - ); - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - } -} - -pub async fn mandates_incoming_webhook_flow( - state: SessionState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - source_verified: bool, - event_type: webhooks::IncomingWebhookEvent, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - if source_verified { - let db = &*state.store; - let mandate = match webhook_details.object_reference_id { - webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( - mandate_id, - )) => db - .find_mandate_by_merchant_id_mandate_id( - &merchant_account.merchant_id, - mandate_id.as_str(), - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, - webhooks::ObjectReferenceId::MandateId( - webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id), - ) => db - .find_mandate_by_merchant_id_connector_mandate_id( - &merchant_account.merchant_id, - connector_mandate_id.as_str(), - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received a non-mandate id for retrieving mandate")?, - }; - let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("event type to mandate status mapping failed")?; - let mandate_id = mandate.mandate_id.clone(); - let updated_mandate = db - .update_mandate_by_merchant_id_mandate_id( - &merchant_account.merchant_id, - &mandate_id, - storage::MandateUpdate::StatusUpdate { mandate_status }, - mandate, - merchant_account.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - let mandates_response = Box::new( - api::mandates::MandateResponse::from_db_mandate( - &state, - key_store.clone(), - updated_mandate.clone(), - merchant_account.storage_scheme, - ) - .await?, - ); - 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( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Mandates, - updated_mandate.mandate_id.clone(), - enums::EventObjectType::MandateDetails, - api::OutgoingWebhookContent::MandateDetails(mandates_response), - Some(updated_mandate.created_at), - ) - .await?; - } - Ok(WebhookResponseTracker::Mandate { - mandate_id: updated_mandate.mandate_id, - status: updated_mandate.mandate_status, - }) - } else { - logger::error!("Webhook source verification failed for mandates webhook flow"); - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - } -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub(crate) async fn frm_incoming_webhook_flow( - state: SessionState, - req_state: ReqState, - merchant_account: domain::MerchantAccount, - key_store: domain::MerchantKeyStore, - source_verified: bool, - event_type: webhooks::IncomingWebhookEvent, - object_ref_id: api::ObjectReferenceId, - business_profile: diesel_models::business_profile::BusinessProfile, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - if source_verified { - let payment_attempt = - get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) - .await?; - let payment_response = match event_type { - webhooks::IncomingWebhookEvent::FrmApproved => { - Box::pin(payments::payments_core::< - api::Capture, - api::PaymentsResponse, - _, - _, - _, - >( - state.clone(), - req_state, - merchant_account.clone(), - key_store.clone(), - payments::PaymentApprove, - api::PaymentsCaptureRequest { - payment_id: payment_attempt.payment_id, - amount_to_capture: payment_attempt.amount_to_capture, - ..Default::default() - }, - services::api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - None, - HeaderPayload::default(), - )) - .await? - } - webhooks::IncomingWebhookEvent::FrmRejected => { - Box::pin(payments::payments_core::< - api::Void, - api::PaymentsResponse, - _, - _, - _, - >( - state.clone(), - req_state, - merchant_account.clone(), - key_store.clone(), - payments::PaymentReject, - api::PaymentsCancelRequest { - payment_id: payment_attempt.payment_id.clone(), - cancellation_reason: Some( - "Rejected by merchant based on FRM decision".to_string(), - ), - ..Default::default() - }, - services::api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - None, - HeaderPayload::default(), - )) - .await? - } - _ => Err(errors::ApiErrorResponse::EventNotFound)?, - }; - match payment_response { - services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { - let payment_id = payments_response - .payment_id - .clone() - .get_required_value("payment_id") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("payment id not received from payments core")?; - let status = payments_response.status; - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); - if let Some(outgoing_event_type) = event_type { - let primary_object_created_at = payments_response.created; - create_event_and_trigger_outgoing_webhook( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Payments, - payment_id.clone(), - enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), - primary_object_created_at, - ) - .await?; - }; - let response = WebhookResponseTracker::Payment { payment_id, status }; - Ok(response) - } - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( - "Did not get payment id as object reference id in webhook payments flow", - )?, - } - } else { - logger::error!("Webhook source verification failed for frm webhooks flow"); - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - } -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub async fn disputes_incoming_webhook_flow( - state: SessionState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - source_verified: bool, - connector: &(dyn api::Connector + Sync), - request_details: &api::IncomingWebhookRequestDetails<'_>, - event_type: webhooks::IncomingWebhookEvent, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); - if source_verified { - let db = &*state.store; - let dispute_details = connector.get_dispute_details(request_details).switch()?; - let payment_attempt = get_payment_attempt_from_object_reference_id( - &state, - webhook_details.object_reference_id, - &merchant_account, - ) - .await?; - let option_dispute = db - .find_by_merchant_id_payment_id_connector_dispute_id( - &merchant_account.merchant_id, - &payment_attempt.payment_id, - &dispute_details.connector_dispute_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?; - let dispute_object = get_or_update_dispute_object( - state.clone(), - option_dispute, - dispute_details, - &merchant_account.merchant_id, - &payment_attempt, - event_type, - &business_profile, - connector.id(), - ) - .await?; - 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( - state, - merchant_account, - business_profile, - &key_store, - event_type, - enums::EventClass::Disputes, - dispute_object.dispute_id.clone(), - enums::EventObjectType::DisputeDetails, - api::OutgoingWebhookContent::DisputeDetails(disputes_response), - Some(dispute_object.created_at), - ) - .await?; - metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(&metrics::CONTEXT, 1, &[]); - Ok(WebhookResponseTracker::Dispute { - dispute_id: dispute_object.dispute_id, - payment_id: dispute_object.payment_id, - status: dispute_object.dispute_status, - }) - } else { - metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - } -} - -async fn bank_transfer_webhook_flow( - state: SessionState, - req_state: ReqState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - key_store: domain::MerchantKeyStore, - webhook_details: api::IncomingWebhookDetails, - source_verified: bool, -) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { - let response = if source_verified { - let payment_attempt = get_payment_attempt_from_object_reference_id( - &state, - webhook_details.object_reference_id, - &merchant_account, - ) - .await?; - let payment_id = payment_attempt.payment_id; - let request = api::PaymentsRequest { - payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( - payment_id, - )), - payment_token: payment_attempt.payment_token, - ..Default::default() - }; - Box::pin(payments::payments_core::< - api::Authorize, - api::PaymentsResponse, - _, - _, - _, - >( - state.clone(), - req_state, - merchant_account.to_owned(), - key_store.clone(), - payments::PaymentConfirm, - request, - services::api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - None, - HeaderPayload::with_source(common_enums::PaymentSource::Webhook), - )) - .await - } else { - Err(report!( - errors::ApiErrorResponse::WebhookAuthenticationFailed - )) - }; - - match response? { - services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { - let payment_id = payments_response - .payment_id - .clone() - .get_required_value("payment_id") - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("did not receive payment id from payments core response")?; - - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); - let status = payments_response.status; - - // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook - if let Some(outgoing_event_type) = event_type { - let primary_object_created_at = payments_response.created; - create_event_and_trigger_outgoing_webhook( - state, - merchant_account, - business_profile, - &key_store, - outgoing_event_type, - enums::EventClass::Payments, - payment_id.clone(), - enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), - primary_object_created_at, - ) - .await?; - } - - Ok(WebhookResponseTracker::Payment { payment_id, status }) - } - - _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("received non-json response from payments core")?, - } -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub(crate) async fn create_event_and_trigger_outgoing_webhook( - state: SessionState, - merchant_account: domain::MerchantAccount, - business_profile: diesel_models::business_profile::BusinessProfile, - merchant_key_store: &domain::MerchantKeyStore, - event_type: enums::EventType, - event_class: enums::EventClass, - primary_object_id: String, - primary_object_type: enums::EventObjectType, - content: api::OutgoingWebhookContent, - primary_object_created_at: Option<time::PrimitiveDateTime>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt; - let idempotent_event_id = - utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt); - let webhook_url_result = get_webhook_url_from_business_profile(&business_profile); - - if !state.conf.webhooks.outgoing_enabled - || webhook_url_result.is_err() - || webhook_url_result.as_ref().is_ok_and(String::is_empty) - { - logger::debug!( - business_profile_id=%business_profile.profile_id, - %idempotent_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 event_id = utils::generate_event_id(); - let merchant_id = business_profile.merchant_id.clone(); - let now = common_utils::date_time::now(); - - let outgoing_webhook = api::OutgoingWebhook { - merchant_id: merchant_id.clone(), - event_id: event_id.clone(), - event_type, - content: content.clone(), - timestamp: now, - }; - - let request_content = get_outgoing_webhook_request( - &merchant_account, - outgoing_webhook, - business_profile.payment_response_hash_key.as_deref(), - ) - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("Failed to construct outgoing webhook request content")?; - - let new_event = domain::Event { - event_id: event_id.clone(), - event_type, - event_class, - is_webhook_notified: false, - primary_object_id, - primary_object_type, - created_at: now, - merchant_id: Some(business_profile.merchant_id.clone()), - business_profile_id: Some(business_profile.profile_id.clone()), - primary_object_created_at, - idempotent_event_id: Some(idempotent_event_id.clone()), - initial_attempt_id: Some(event_id.clone()), - request: Some( - domain_types::encrypt( - request_content - .encode_to_string_of_json() - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("Failed to encode outgoing webhook request content") - .map(Secret::new)?, - merchant_key_store.key.get_inner().peek(), - ) - .await - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("Failed to encrypt outgoing webhook request content")?, - ), - response: None, - delivery_attempt: Some(delivery_attempt), - }; - - let event_insert_result = state - .store - .insert_event(new_event, merchant_key_store) - .await; - - let event = match event_insert_result { - Ok(event) => Ok(event), - Err(error) => { - if error.current_context().is_db_unique_violation() { - logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database"); - return Ok(()); - } else { - logger::error!(event_insertion_failure=?error); - Err(error - .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) - .attach_printable("Failed to insert event in events table")) - } - } - }?; - - 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 cloned_key_store = merchant_key_store.clone(); - // Using a tokio spawn here and not arbiter because not all caller of this function - // may have an actix arbiter - tokio::spawn( - async move { - Box::pin(trigger_webhook_and_raise_event( - state, - business_profile, - &cloned_key_store, - event, - request_content, - delivery_attempt, - Some(content), - process_tracker, - )) - .await; - } - .in_current_span(), - ); - - Ok(()) -} - -#[allow(clippy::too_many_arguments)] -#[instrument(skip_all)] -pub(crate) async fn trigger_webhook_and_raise_event( - state: SessionState, - business_profile: diesel_models::business_profile::BusinessProfile, - merchant_key_store: &domain::MerchantKeyStore, - event: domain::Event, - request_content: OutgoingWebhookRequestContent, - delivery_attempt: enums::WebhookDeliveryAttempt, - content: Option<api::OutgoingWebhookContent>, - process_tracker: Option<storage::ProcessTracker>, -) { - logger::debug!( - event_id=%event.event_id, - idempotent_event_id=?event.idempotent_event_id, - initial_attempt_id=?event.initial_attempt_id, - "Attempting to send webhook" - ); - - let merchant_id = business_profile.merchant_id.clone(); - let trigger_webhook_result = trigger_webhook_to_merchant( - state.clone(), - business_profile, - merchant_key_store, - event.clone(), - request_content, - delivery_attempt, - process_tracker, - ) - .await; - - raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event); -} - -async fn trigger_webhook_to_merchant( - state: SessionState, - business_profile: diesel_models::business_profile::BusinessProfile, - merchant_key_store: &domain::MerchantKeyStore, - event: domain::Event, - request_content: OutgoingWebhookRequestContent, - delivery_attempt: enums::WebhookDeliveryAttempt, - process_tracker: Option<storage::ProcessTracker>, -) -> CustomResult<(), errors::WebhooksFlowError> { - 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 event_id = event.event_id; - - let headers = request_content - .headers - .into_iter() - .map(|(name, value)| (name, value.into_masked())) - .collect(); - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&webhook_url) - .attach_default_headers() - .headers(headers) - .set_body(RequestContent::RawBytes( - request_content.body.expose().into_bytes(), - )) - .build(); - - let response = state - .api_client - .send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false) - .await; - - metrics::WEBHOOK_OUTGOING_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - business_profile.merchant_id.clone(), - )], - ); - logger::debug!(outgoing_webhook_response=?response); - - let update_event_if_client_error = - |state: SessionState, - merchant_key_store: domain::MerchantKeyStore, - merchant_id: String, - event_id: String, - error_message: String| async move { - let is_webhook_notified = false; - - let response_to_store = OutgoingWebhookResponseContent { - body: None, - headers: None, - status_code: None, - error_message: Some(error_message), - }; - - let event_update = domain::EventUpdate::UpdateResponse { - is_webhook_notified, - response: Some( - domain_types::encrypt( - response_to_store - .encode_to_string_of_json() - .change_context( - errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, - ) - .map(Secret::new)?, - merchant_key_store.key.get_inner().peek(), - ) - .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) - .attach_printable("Failed to encrypt outgoing webhook response content")?, - ), - }; - - state - .store - .update_event_by_merchant_id_event_id( - &merchant_id, - &event_id, - event_update, - &merchant_key_store, - ) - .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) - }; - - let api_client_error_handler = - |state: SessionState, - merchant_key_store: domain::MerchantKeyStore, - merchant_id: String, - event_id: String, - client_error: error_stack::Report<errors::ApiClientError>, - delivery_attempt: enums::WebhookDeliveryAttempt| async move { - // Not including detailed error message in response information since it contains too - // much of diagnostic information to be exposed to the merchant. - update_event_if_client_error( - state, - merchant_key_store, - merchant_id, - event_id, - "Unable to send request to merchant server".to_string(), - ) - .await?; - - let error = - client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed); - logger::error!( - ?error, - ?delivery_attempt, - "An error occurred when sending webhook to merchant" - ); - - Ok::<_, error_stack::Report<errors::WebhooksFlowError>>(()) - }; - let update_event_in_storage = |state: SessionState, - merchant_key_store: domain::MerchantKeyStore, - merchant_id: String, - event_id: String, - response: reqwest::Response| async move { - let status_code = response.status(); - let is_webhook_notified = status_code.is_success(); - - let response_headers = response - .headers() - .iter() - .map(|(name, value)| { - ( - name.as_str().to_owned(), - value - .to_str() - .map(|s| Secret::from(String::from(s))) - .unwrap_or_else(|error| { - logger::warn!( - "Response header {} contains non-UTF-8 characters: {error:?}", - name.as_str() - ); - Secret::from(String::from("Non-UTF-8 header value")) - }), - ) - }) - .collect::<Vec<_>>(); - let response_body = response - .text() - .await - .map(Secret::from) - .unwrap_or_else(|error| { - logger::warn!("Response contains non-UTF-8 characters: {error:?}"); - Secret::from(String::from("Non-UTF-8 response body")) - }); - let response_to_store = OutgoingWebhookResponseContent { - body: Some(response_body), - headers: Some(response_headers), - status_code: Some(status_code.as_u16()), - error_message: None, - }; - - let event_update = domain::EventUpdate::UpdateResponse { - is_webhook_notified, - response: Some( - domain_types::encrypt( - response_to_store - .encode_to_string_of_json() - .change_context( - errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, - ) - .map(Secret::new)?, - merchant_key_store.key.get_inner().peek(), - ) - .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) - .attach_printable("Failed to encrypt outgoing webhook response content")?, - ), - }; - state - .store - .update_event_by_merchant_id_event_id( - &merchant_id, - &event_id, - event_update, - &merchant_key_store, - ) - .await - .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) - }; - let increment_webhook_outgoing_received_count = |merchant_id: String| { - metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], - ) - }; - let success_response_handler = - |state: SessionState, - merchant_id: String, - process_tracker: Option<storage::ProcessTracker>, - business_status: &'static str| async move { - increment_webhook_outgoing_received_count(merchant_id); - - match process_tracker { - Some(process_tracker) => state - .store - .as_scheduler() - .finish_process_with_business_status(process_tracker, business_status.into()) - .await - .change_context( - errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, - ), - None => Ok(()), - } - }; - let error_response_handler = |merchant_id: String, - delivery_attempt: enums::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 { - enums::WebhookDeliveryAttempt::InitialAttempt => match response { - Err(client_error) => { - api_client_error_handler( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - client_error, - delivery_attempt, - ) - .await? - } - Ok(response) => { - let status_code = response.status(); - let _updated_event = update_event_in_storage( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - response, - ) - .await?; - - if status_code.is_success() { - success_response_handler( - state.clone(), - business_profile.merchant_id, - process_tracker, - "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL", - ) - .await?; - } else { - error_response_handler( - business_profile.merchant_id, - delivery_attempt, - status_code.as_u16(), - "Ignoring error when sending webhook to merchant", - ); - } - } - }, - enums::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( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - client_error, - delivery_attempt, - ) - .await?; - // 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) => { - let status_code = response.status(); - let _updated_event = update_event_in_storage( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - response, - ) - .await?; - - if status_code.is_success() { - success_response_handler( - state.clone(), - business_profile.merchant_id, - Some(process_tracker), - "COMPLETED_BY_PT", - ) - .await?; - } else { - error_response_handler( - business_profile.merchant_id.clone(), - delivery_attempt, - status_code.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, - )?; - } - } - } - } - enums::WebhookDeliveryAttempt::ManualRetry => match response { - Err(client_error) => { - api_client_error_handler( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - client_error, - delivery_attempt, - ) - .await? - } - Ok(response) => { - let status_code = response.status(); - let _updated_event = update_event_in_storage( - state.clone(), - merchant_key_store.clone(), - business_profile.merchant_id.clone(), - event_id.clone(), - response, - ) - .await?; - - if status_code.is_success() { - increment_webhook_outgoing_received_count(business_profile.merchant_id.clone()); - } else { - error_response_handler( - business_profile.merchant_id, - delivery_attempt, - status_code.as_u16(), - "Ignoring error when sending webhook to merchant", - ); - } - } - }, - } - - Ok(()) -} - -fn raise_webhooks_analytics_event( - state: SessionState, - trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, - content: Option<api::OutgoingWebhookContent>, - merchant_id: String, - event: domain::Event, -) { - 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()) - .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 - .as_ref() - .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content); - let webhook_event = OutgoingWebhookEvent::new( - merchant_id, - event.event_id, - event.event_type, - outgoing_webhook_event_content, - error, - event.initial_attempt_id, - ); - state.event_handler().log_event(&webhook_event); -} - -#[allow(clippy::too_many_arguments)] -pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>( - flow: &impl router_env::types::FlowMetric, - state: SessionState, - req_state: ReqState, - req: &actix_web::HttpRequest, - merchant_account: domain::MerchantAccount, - key_store: domain::MerchantKeyStore, - connector_name_or_mca_id: &str, - body: actix_web::web::Bytes, -) -> RouterResponse<serde_json::Value> { - let start_instant = Instant::now(); - let (application_response, webhooks_response_tracker, serialized_req) = - Box::pin(webhooks_core::<W>( - state.clone(), - req_state, - req, - merchant_account.clone(), - key_store, - connector_name_or_mca_id, - body.clone(), - )) - .await?; - - logger::info!(incoming_webhook_payload = ?serialized_req); - - let request_duration = Instant::now() - .saturating_duration_since(start_instant) - .as_millis(); - - let request_id = RequestId::extract(req) - .await - .attach_printable("Unable to extract request id from request") - .change_context(errors::ApiErrorResponse::InternalServerError)?; - let auth_type = auth::AuthenticationType::WebhookAuth { - merchant_id: merchant_account.merchant_id.clone(), - }; - let status_code = 200; - let api_event = ApiEventsType::Webhooks { - connector: connector_name_or_mca_id.to_string(), - payment_id: webhooks_response_tracker.get_payment_id(), - }; - let response_value = serde_json::to_value(&webhooks_response_tracker) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not convert webhook effect to string")?; - - let api_event = ApiEvent::new( - Some(merchant_account.merchant_id.clone()), - flow, - &request_id, - request_duration, - status_code, - serialized_req, - Some(response_value), - None, - auth_type, - None, - api_event, - req, - req.method(), - ); - state.event_handler().log_event(&api_event); - Ok(application_response) -} - -#[instrument(skip_all)] -pub async fn webhooks_core<W: types::OutgoingWebhookType>( - state: SessionState, - req_state: ReqState, - req: &actix_web::HttpRequest, - merchant_account: domain::MerchantAccount, - key_store: domain::MerchantKeyStore, - connector_name_or_mca_id: &str, - body: actix_web::web::Bytes, -) -> errors::RouterResult<( - services::ApplicationResponse<serde_json::Value>, - WebhookResponseTracker, - serde_json::Value, -)> { - metrics::WEBHOOK_INCOMING_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - merchant_account.merchant_id.clone(), - )], - ); - let mut request_details = api::IncomingWebhookRequestDetails { - method: req.method().clone(), - uri: req.uri().clone(), - headers: req.headers(), - query_params: req.query_string().to_string(), - body: &body, - }; - - // Fetch the merchant connector account to get the webhooks source secret - // `webhooks source secret` is a secret shared between the merchant and connector - // This is used for source verification and webhooks integrity - let (merchant_connector_account, connector, connector_name) = fetch_optional_mca_and_connector( - &state, - &merchant_account, - connector_name_or_mca_id, - &key_store, - ) - .await?; - - let decoded_body = connector - .decode_webhook_body( - &*state.clone().store, - &request_details, - &merchant_account.merchant_id, - ) - .await - .switch() - .attach_printable("There was an error in incoming webhook body decoding")?; - - request_details.body = &decoded_body; - - let event_type = match connector - .get_webhook_event_type(&request_details) - .allow_webhook_event_type_not_found( - state - .clone() - .conf - .webhooks - .ignore_error - .event_type - .unwrap_or(true), - ) - .switch() - .attach_printable("Could not find event type in incoming webhook body")? - { - Some(event_type) => event_type, - // Early return allows us to acknowledge the webhooks that we do not support - None => { - logger::error!( - webhook_payload =? request_details.body, - "Failed while identifying the event type", - ); - - metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( - &metrics::CONTEXT, - 1, - &[ - metrics::KeyValue::new(MERCHANT_ID, merchant_account.merchant_id.clone()), - metrics::KeyValue::new("connector", connector_name.to_string()), - ], - ); - - let response = connector - .get_webhook_api_response(&request_details) - .switch() - .attach_printable("Failed while early return in case of event type parsing")?; - - return Ok(( - response, - WebhookResponseTracker::NoEffect, - serde_json::Value::Null, - )); - } - }; - logger::info!(event_type=?event_type); - - let is_webhook_event_supported = !matches!( - event_type, - webhooks::IncomingWebhookEvent::EventNotSupported - ); - let is_webhook_event_enabled = !utils::is_webhook_event_disabled( - &*state.clone().store, - connector_name.as_str(), - &merchant_account.merchant_id, - &event_type, - ) - .await; - - //process webhook further only if webhook event is enabled and is not event_not_supported - let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; - - logger::info!(process_webhook=?process_webhook_further); - - let flow_type: api::WebhookFlow = event_type.into(); - let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); - let webhook_effect = if process_webhook_further - && !matches!(flow_type, api::WebhookFlow::ReturnResponse) - { - let object_ref_id = connector - .get_webhook_object_reference_id(&request_details) - .switch() - .attach_printable("Could not find object reference id in incoming webhook body")?; - let connector_enum = api_models::enums::Connector::from_str(&connector_name) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "connector", - }) - .attach_printable_lazy(|| { - format!("unable to parse connector name {connector_name:?}") - })?; - let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; - - let merchant_connector_account = match merchant_connector_account { - Some(merchant_connector_account) => merchant_connector_account, - None => { - helper_utils::get_mca_from_object_reference_id( - &*state.clone().store, - object_ref_id.clone(), - &merchant_account, - &connector_name, - &key_store, - ) - .await? - } - }; - - let source_verified = if connectors_with_source_verification_call - .connectors_with_webhook_source_verification_call - .contains(&connector_enum) - { - connector - .verify_webhook_source_verification_call( - &state, - &merchant_account, - merchant_connector_account.clone(), - &connector_name, - &request_details, - ) - .await - .or_else(|error| match error.current_context() { - errors::ConnectorError::WebhookSourceVerificationFailed => { - logger::error!(?error, "Source Verification Failed"); - Ok(false) - } - _ => Err(error), - }) - .switch() - .attach_printable("There was an issue in incoming webhook source verification")? - } else { - connector - .verify_webhook_source( - &request_details, - &merchant_account, - merchant_connector_account.clone(), - connector_name.as_str(), - ) - .await - .or_else(|error| match error.current_context() { - errors::ConnectorError::WebhookSourceVerificationFailed => { - logger::error!(?error, "Source Verification Failed"); - Ok(false) - } - _ => Err(error), - }) - .switch() - .attach_printable("There was an issue in incoming webhook source verification")? - }; - - if source_verified { - metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - merchant_account.merchant_id.clone(), - )], - ); - } else if connector.is_webhook_source_verification_mandatory() { - // if webhook consumption is mandatory for connector, fail webhook - // so that merchant can retrigger it after updating merchant_secret - return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); - } - - logger::info!(source_verified=?source_verified); - - event_object = connector - .get_webhook_resource_object(&request_details) - .switch() - .attach_printable("Could not find resource object in incoming webhook body")?; - - let webhook_details = api::IncomingWebhookDetails { - object_reference_id: object_ref_id.clone(), - resource_object: serde_json::to_vec(&event_object) - .change_context(errors::ParsingError::EncodeError("byte-vec")) - .attach_printable("Unable to convert webhook payload to a value") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "There was an issue when encoding the incoming webhook body to bytes", - )?, - }; - - let profile_id = merchant_connector_account - .profile_id - .as_ref() - .get_required_value("profile_id") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not find profile_id in merchant connector account")?; - - let business_profile = state - .store - .find_business_profile_by_profile_id(profile_id) - .await - .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { - id: profile_id.to_string(), - })?; - - match flow_type { - api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( - state.clone(), - req_state, - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - )) - .await - .attach_printable("Incoming webhook flow for payments failed")?, - - api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - connector_name.as_str(), - source_verified, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for refunds failed")?, - - api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - connector, - &request_details, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for disputes failed")?, - - api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( - state.clone(), - req_state, - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - )) - .await - .attach_printable("Incoming bank-transfer webhook flow failed")?, - - api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, - - api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for mandates failed")?, - - api::WebhookFlow::ExternalAuthentication => { - Box::pin(external_authentication_incoming_webhook_flow( - state.clone(), - req_state, - merchant_account, - key_store, - source_verified, - event_type, - &request_details, - connector, - object_ref_id, - business_profile, - merchant_connector_account, - )) - .await - .attach_printable("Incoming webhook flow for external authentication failed")? - } - api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( - state.clone(), - req_state, - merchant_account, - key_store, - source_verified, - event_type, - object_ref_id, - business_profile, - )) - .await - .attach_printable("Incoming webhook flow for fraud check failed")?, - - #[cfg(feature = "payouts")] - api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - event_type, - source_verified, - )) - .await - .attach_printable("Incoming webhook flow for payouts failed")?, - - _ => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unsupported Flow Type received in incoming webhooks")?, - } - } else { - metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( - &metrics::CONTEXT, - 1, - &[metrics::KeyValue::new( - MERCHANT_ID, - merchant_account.merchant_id.clone(), - )], - ); - WebhookResponseTracker::NoEffect - }; - - let response = connector - .get_webhook_api_response(&request_details) - .switch() - .attach_printable("Could not get incoming webhook api response from connector")?; - - let serialized_request = event_object - .masked_serialize() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not convert webhook effect to string")?; - Ok((response, webhook_effect, serialized_request)) -} - -#[inline] -pub async fn get_payment_id( - db: &dyn StorageInterface, - payment_id: &api::PaymentIdType, - merchant_id: &str, - storage_scheme: enums::MerchantStorageScheme, -) -> errors::RouterResult<String> { - let pay_id = || async { - match payment_id { - api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_string()), - api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db - .find_payment_attempt_by_merchant_id_connector_txn_id( - merchant_id, - id, - storage_scheme, - ) - .await - .map(|p| p.payment_id), - api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db - .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) - .await - .map(|p| p.payment_id), - api_models::payments::PaymentIdType::PreprocessingId(ref id) => db - .find_payment_attempt_by_preprocessing_id_merchant_id( - id, - merchant_id, - storage_scheme, - ) - .await - .map(|p| p.payment_id), - } - }; - - pay_id() - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) -} - -fn get_connector_by_connector_name( - state: &SessionState, - connector_name: &str, - merchant_connector_id: Option<String>, -) -> CustomResult<(&'static (dyn api::Connector + Sync), String), errors::ApiErrorResponse> { - let authentication_connector = - api_models::enums::convert_authentication_connector(connector_name); - #[cfg(feature = "frm")] - { - let frm_connector = api_models::enums::convert_frm_connector(connector_name); - if frm_connector.is_some() { - let frm_connector_data = - api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; - return Ok(( - *frm_connector_data.connector, - frm_connector_data.connector_name.to_string(), - )); - } - } - - let (connector, connector_name) = if authentication_connector.is_some() { - let authentication_connector_data = - api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; - ( - authentication_connector_data.connector, - authentication_connector_data.connector_name.to_string(), - ) - } else { - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - connector_name, - api::GetToken::Connector, - merchant_connector_id, - ) - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "invalid connector name received".to_string(), - }) - .attach_printable("Failed construction of ConnectorData")?; - ( - connector_data.connector, - connector_data.connector_name.to_string(), - ) - }; - Ok((*connector, connector_name)) -} - -/// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id}) -/// if merchant connector id is not passed in the request, then this will return None for mca -async fn fetch_optional_mca_and_connector( - state: &SessionState, - merchant_account: &domain::MerchantAccount, - connector_name_or_mca_id: &str, - key_store: &domain::MerchantKeyStore, -) -> CustomResult< - ( - Option<domain::MerchantConnectorAccount>, - &'static (dyn api::Connector + Sync), - String, - ), - errors::ApiErrorResponse, -> { - let db = &state.store; - if connector_name_or_mca_id.starts_with("mca_") { - let mca = db - .find_by_merchant_connector_account_merchant_id_merchant_connector_id( - &merchant_account.merchant_id, - connector_name_or_mca_id, - key_store, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { - id: connector_name_or_mca_id.to_string(), - }) - .attach_printable( - "error while fetching merchant_connector_account from connector_id", - )?; - let (connector, connector_name) = get_connector_by_connector_name( - state, - &mca.connector_name, - Some(mca.merchant_connector_id.clone()), - )?; - - Ok((Some(mca), connector, connector_name)) - } else { - // Merchant connector account is already being queried, it is safe to set connector id as None - let (connector, connector_name) = - get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; - Ok((None, connector, connector_name)) - } -} - -pub async fn add_outgoing_webhook_retry_task_to_process_tracker( - db: &dyn StorageInterface, - business_profile: &diesel_models::business_profile::BusinessProfile, - event: &domain::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 - )) - .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, - initial_attempt_id: event.initial_attempt_id.clone(), - }; - - 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.event_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) - } - } -} - -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) -} - -pub(crate) fn get_outgoing_webhook_request( - merchant_account: &domain::MerchantAccount, - outgoing_webhook: api::OutgoingWebhook, - payment_response_hash_key: Option<&str>, -) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { - #[inline] - fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>( - outgoing_webhook: api::OutgoingWebhook, - payment_response_hash_key: Option<&str>, - ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { - let mut headers = vec![( - reqwest::header::CONTENT_TYPE.to_string(), - mime::APPLICATION_JSON.essence_str().into(), - )]; - - let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook); - - let outgoing_webhooks_signature = transformed_outgoing_webhook - .get_outgoing_webhooks_signature(payment_response_hash_key)?; - - if let Some(signature) = outgoing_webhooks_signature.signature { - WebhookType::add_webhook_header(&mut headers, signature) - } - - Ok(OutgoingWebhookRequestContent { - body: outgoing_webhooks_signature.payload, - headers: headers - .into_iter() - .map(|(name, value)| (name, Secret::new(value.into_inner()))) - .collect(), - }) - } - - match merchant_account.get_compatible_connector() { - #[cfg(feature = "stripe")] - Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::< - stripe_webhooks::StripeOutgoingWebhook, - >( - outgoing_webhook, payment_response_hash_key - ), - _ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( - outgoing_webhook, - payment_response_hash_key, - ), - } -} diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs new file mode 100644 index 00000000000..2f1a37981ec --- /dev/null +++ b/crates/router/src/core/webhooks/incoming.rs @@ -0,0 +1,1628 @@ +use std::{str::FromStr, time::Instant}; + +use actix_web::FromRequest; +#[cfg(feature = "payouts")] +use api_models::payouts as payout_models; +use api_models::{ + payments::HeaderPayload, + webhooks::{self, WebhookResponseTracker}, +}; +use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; +use error_stack::{report, ResultExt}; +use masking::ExposeInterface; +use router_env::{instrument, tracing, tracing_actix_web::RequestId}; + +use super::{types, utils, MERCHANT_ID}; +use crate::{ + consts, + core::{ + api_locking, + errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, + metrics, payments, refunds, utils as core_utils, + }, + db::StorageInterface, + events::api_logs::ApiEvent, + logger, + routes::{ + app::{ReqState, SessionStateInfo}, + lock_utils, + metrics::request::add_attributes, + SessionState, + }, + services::{self, authentication as auth}, + types::{ + api::{self, mandates::MandateResponseExt}, + domain, + storage::{self, enums}, + transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, + }, + utils::{self as helper_utils, generate_id, OptionExt}, +}; +#[cfg(feature = "payouts")] +use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; + +#[allow(clippy::too_many_arguments)] +pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( + flow: &impl router_env::types::FlowMetric, + state: SessionState, + req_state: ReqState, + req: &actix_web::HttpRequest, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + connector_name_or_mca_id: &str, + body: actix_web::web::Bytes, +) -> RouterResponse<serde_json::Value> { + let start_instant = Instant::now(); + let (application_response, webhooks_response_tracker, serialized_req) = + Box::pin(incoming_webhooks_core::<W>( + state.clone(), + req_state, + req, + merchant_account.clone(), + key_store, + connector_name_or_mca_id, + body.clone(), + )) + .await?; + + logger::info!(incoming_webhook_payload = ?serialized_req); + + let request_duration = Instant::now() + .saturating_duration_since(start_instant) + .as_millis(); + + let request_id = RequestId::extract(req) + .await + .attach_printable("Unable to extract request id from request") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let auth_type = auth::AuthenticationType::WebhookAuth { + merchant_id: merchant_account.merchant_id.clone(), + }; + let status_code = 200; + let api_event = ApiEventsType::Webhooks { + connector: connector_name_or_mca_id.to_string(), + payment_id: webhooks_response_tracker.get_payment_id(), + }; + let response_value = serde_json::to_value(&webhooks_response_tracker) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert webhook effect to string")?; + + let api_event = ApiEvent::new( + Some(merchant_account.merchant_id.clone()), + flow, + &request_id, + request_duration, + status_code, + serialized_req, + Some(response_value), + None, + auth_type, + None, + api_event, + req, + req.method(), + ); + state.event_handler().log_event(&api_event); + Ok(application_response) +} + +#[instrument(skip_all)] +async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( + state: SessionState, + req_state: ReqState, + req: &actix_web::HttpRequest, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + connector_name_or_mca_id: &str, + body: actix_web::web::Bytes, +) -> errors::RouterResult<( + services::ApplicationResponse<serde_json::Value>, + WebhookResponseTracker, + serde_json::Value, +)> { + metrics::WEBHOOK_INCOMING_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new( + MERCHANT_ID, + merchant_account.merchant_id.clone(), + )], + ); + let mut request_details = api::IncomingWebhookRequestDetails { + method: req.method().clone(), + uri: req.uri().clone(), + headers: req.headers(), + query_params: req.query_string().to_string(), + body: &body, + }; + + // Fetch the merchant connector account to get the webhooks source secret + // `webhooks source secret` is a secret shared between the merchant and connector + // This is used for source verification and webhooks integrity + let (merchant_connector_account, connector, connector_name) = fetch_optional_mca_and_connector( + &state, + &merchant_account, + connector_name_or_mca_id, + &key_store, + ) + .await?; + + let decoded_body = connector + .decode_webhook_body( + &*state.clone().store, + &request_details, + &merchant_account.merchant_id, + ) + .await + .switch() + .attach_printable("There was an error in incoming webhook body decoding")?; + + request_details.body = &decoded_body; + + let event_type = match connector + .get_webhook_event_type(&request_details) + .allow_webhook_event_type_not_found( + state + .clone() + .conf + .webhooks + .ignore_error + .event_type + .unwrap_or(true), + ) + .switch() + .attach_printable("Could not find event type in incoming webhook body")? + { + Some(event_type) => event_type, + // Early return allows us to acknowledge the webhooks that we do not support + None => { + logger::error!( + webhook_payload =? request_details.body, + "Failed while identifying the event type", + ); + + metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( + &metrics::CONTEXT, + 1, + &[ + metrics::KeyValue::new(MERCHANT_ID, merchant_account.merchant_id.clone()), + metrics::KeyValue::new("connector", connector_name.to_string()), + ], + ); + + let response = connector + .get_webhook_api_response(&request_details) + .switch() + .attach_printable("Failed while early return in case of event type parsing")?; + + return Ok(( + response, + WebhookResponseTracker::NoEffect, + serde_json::Value::Null, + )); + } + }; + logger::info!(event_type=?event_type); + + let is_webhook_event_supported = !matches!( + event_type, + webhooks::IncomingWebhookEvent::EventNotSupported + ); + let is_webhook_event_enabled = !utils::is_webhook_event_disabled( + &*state.clone().store, + connector_name.as_str(), + &merchant_account.merchant_id, + &event_type, + ) + .await; + + //process webhook further only if webhook event is enabled and is not event_not_supported + let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; + + logger::info!(process_webhook=?process_webhook_further); + + let flow_type: api::WebhookFlow = event_type.into(); + let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); + let webhook_effect = if process_webhook_further + && !matches!(flow_type, api::WebhookFlow::ReturnResponse) + { + let object_ref_id = connector + .get_webhook_object_reference_id(&request_details) + .switch() + .attach_printable("Could not find object reference id in incoming webhook body")?; + let connector_enum = api_models::enums::Connector::from_str(&connector_name) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; + + let merchant_connector_account = match merchant_connector_account { + Some(merchant_connector_account) => merchant_connector_account, + None => { + helper_utils::get_mca_from_object_reference_id( + &*state.clone().store, + object_ref_id.clone(), + &merchant_account, + &connector_name, + &key_store, + ) + .await? + } + }; + + let source_verified = if connectors_with_source_verification_call + .connectors_with_webhook_source_verification_call + .contains(&connector_enum) + { + connector + .verify_webhook_source_verification_call( + &state, + &merchant_account, + merchant_connector_account.clone(), + &connector_name, + &request_details, + ) + .await + .or_else(|error| match error.current_context() { + errors::ConnectorError::WebhookSourceVerificationFailed => { + logger::error!(?error, "Source Verification Failed"); + Ok(false) + } + _ => Err(error), + }) + .switch() + .attach_printable("There was an issue in incoming webhook source verification")? + } else { + connector + .verify_webhook_source( + &request_details, + &merchant_account, + merchant_connector_account.clone(), + connector_name.as_str(), + ) + .await + .or_else(|error| match error.current_context() { + errors::ConnectorError::WebhookSourceVerificationFailed => { + logger::error!(?error, "Source Verification Failed"); + Ok(false) + } + _ => Err(error), + }) + .switch() + .attach_printable("There was an issue in incoming webhook source verification")? + }; + + if source_verified { + metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new( + MERCHANT_ID, + merchant_account.merchant_id.clone(), + )], + ); + } else if connector.is_webhook_source_verification_mandatory() { + // if webhook consumption is mandatory for connector, fail webhook + // so that merchant can retrigger it after updating merchant_secret + return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); + } + + logger::info!(source_verified=?source_verified); + + event_object = connector + .get_webhook_resource_object(&request_details) + .switch() + .attach_printable("Could not find resource object in incoming webhook body")?; + + let webhook_details = api::IncomingWebhookDetails { + object_reference_id: object_ref_id.clone(), + resource_object: serde_json::to_vec(&event_object) + .change_context(errors::ParsingError::EncodeError("byte-vec")) + .attach_printable("Unable to convert webhook payload to a value") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "There was an issue when encoding the incoming webhook body to bytes", + )?, + }; + + let profile_id = merchant_connector_account + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not find profile_id in merchant connector account")?; + + let business_profile = state + .store + .find_business_profile_by_profile_id(profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { + id: profile_id.to_string(), + })?; + + match flow_type { + api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( + state.clone(), + req_state, + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for payments failed")?, + + api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + connector_name.as_str(), + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for refunds failed")?, + + api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + connector, + &request_details, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for disputes failed")?, + + api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( + state.clone(), + req_state, + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + )) + .await + .attach_printable("Incoming bank-transfer webhook flow failed")?, + + api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, + + api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for mandates failed")?, + + api::WebhookFlow::ExternalAuthentication => { + Box::pin(external_authentication_incoming_webhook_flow( + state.clone(), + req_state, + merchant_account, + key_store, + source_verified, + event_type, + &request_details, + connector, + object_ref_id, + business_profile, + merchant_connector_account, + )) + .await + .attach_printable("Incoming webhook flow for external authentication failed")? + } + api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( + state.clone(), + req_state, + merchant_account, + key_store, + source_verified, + event_type, + object_ref_id, + business_profile, + )) + .await + .attach_printable("Incoming webhook flow for fraud check failed")?, + + #[cfg(feature = "payouts")] + api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + event_type, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for payouts failed")?, + + _ => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unsupported Flow Type received in incoming webhooks")?, + } + } else { + metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new( + MERCHANT_ID, + merchant_account.merchant_id.clone(), + )], + ); + WebhookResponseTracker::NoEffect + }; + + let response = connector + .get_webhook_api_response(&request_details) + .switch() + .attach_printable("Could not get incoming webhook api response from connector")?; + + let serialized_request = event_object + .masked_serialize() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert webhook effect to string")?; + Ok((response, webhook_effect, serialized_request)) +} + +#[instrument(skip_all)] +async fn payments_incoming_webhook_flow( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + source_verified: bool, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let consume_or_trigger_flow = if source_verified { + payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) + } else { + payments::CallConnectorAction::Trigger + }; + let payments_response = match webhook_details.object_reference_id { + webhooks::ObjectReferenceId::PaymentId(id) => { + let payment_id = get_payment_id( + state.store.as_ref(), + &id, + merchant_account.merchant_id.as_str(), + merchant_account.storage_scheme, + ) + .await?; + + let lock_action = api_locking::LockAction::Hold { + input: api_locking::LockingInput { + unique_locking_key: payment_id, + api_identifier: lock_utils::ApiIdentifier::Payments, + override_lock_retries: None, + }, + }; + + lock_action + .clone() + .perform_locking_action(&state, merchant_account.merchant_id.to_string()) + .await?; + + let response = Box::pin(payments::payments_core::< + api::PSync, + api::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + merchant_account.clone(), + key_store.clone(), + payments::operations::PaymentStatus, + api::PaymentsRetrieveRequest { + resource_id: id, + merchant_id: Some(merchant_account.merchant_id.clone()), + force_sync: true, + connector: None, + param: None, + merchant_connector_details: None, + client_secret: None, + expand_attempts: None, + expand_captures: None, + }, + services::AuthFlow::Merchant, + consume_or_trigger_flow, + None, + HeaderPayload::default(), + )) + .await; + + lock_action + .free_lock_action(&state, merchant_account.merchant_id.to_owned()) + .await?; + + match response { + Ok(value) => value, + Err(err) + if matches!( + err.current_context(), + &errors::ApiErrorResponse::PaymentNotFound + ) && state + .conf + .webhooks + .ignore_error + .payment_not_found + .unwrap_or(true) => + { + metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( + &metrics::CONTEXT, + 1, + &[add_attributes( + "merchant_id", + merchant_account.merchant_id.clone(), + )], + ); + return Ok(WebhookResponseTracker::NoEffect); + } + error @ Err(_) => error?, + } + } + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( + "Did not get payment id as object reference id in webhook payments flow", + )?, + }; + + match payments_response { + services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + let payment_id = payments_response + .payment_id + .clone() + .get_required_value("payment_id") + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment id not received from payments core")?; + + let status = payments_response.status; + + let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + + // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook + if let Some(outgoing_event_type) = event_type { + let primary_object_created_at = payments_response.created; + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Payments, + payment_id.clone(), + enums::EventObjectType::PaymentDetails, + api::OutgoingWebhookContent::PaymentDetails(payments_response), + primary_object_created_at, + ) + .await?; + }; + + let response = WebhookResponseTracker::Payment { payment_id, status }; + + Ok(response) + } + + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received non-json response from payments core")?, + } +} + +#[cfg(feature = "payouts")] +#[instrument(skip_all)] +async fn payouts_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + event_type: webhooks::IncomingWebhookEvent, + source_verified: bool, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); + if source_verified { + let db = &*state.store; + //find payout_attempt by object_reference_id + let payout_attempt = match webhook_details.object_reference_id { + webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type { + webhooks::PayoutIdType::PayoutAttemptId(id) => db + .find_payout_attempt_by_merchant_id_payout_attempt_id( + &merchant_account.merchant_id, + &id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the payout attempt")?, + webhooks::PayoutIdType::ConnectorPayoutId(id) => db + .find_payout_attempt_by_merchant_id_connector_payout_id( + &merchant_account.merchant_id, + &id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the payout attempt")?, + }, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received a non-payout id when processing payout webhooks")?, + }; + + let payouts = db + .find_payout_by_merchant_id_payout_id( + &merchant_account.merchant_id, + &payout_attempt.payout_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the payout")?; + + let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate { + connector_payout_id: payout_attempt.connector_payout_id.clone(), + status: common_enums::PayoutStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed payout status mapping from event type")?, + error_message: None, + error_code: None, + is_eligible: payout_attempt.is_eligible, + }; + + let action_req = + payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest { + payout_id: payouts.payout_id.clone(), + }); + + let payout_data = + payouts::make_payout_data(&state, &merchant_account, &key_store, &action_req).await?; + + let updated_payout_attempt = db + .update_payout_attempt( + &payout_attempt, + payout_attempt_update, + &payout_data.payouts, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable_lazy(|| { + format!( + "Failed while updating payout attempt: payout_attempt_id: {}", + payout_attempt.payout_attempt_id + ) + })?; + + let event_type: Option<enums::EventType> = updated_payout_attempt.status.foreign_into(); + + // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook + if let Some(outgoing_event_type) = event_type { + let router_response = + payouts::response_handler(&merchant_account, &payout_data).await?; + + let payout_create_response: payout_models::PayoutCreateResponse = match router_response + { + services::ApplicationResponse::Json(response) => response, + _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the payout create response")?, + }; + + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Payouts, + updated_payout_attempt.payout_id.clone(), + enums::EventObjectType::PayoutDetails, + api::OutgoingWebhookContent::PayoutDetails(payout_create_response), + Some(updated_payout_attempt.created_at), + ) + .await?; + } + + Ok(WebhookResponseTracker::Payout { + payout_id: updated_payout_attempt.payout_id, + status: updated_payout_attempt.status, + }) + } else { + metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + } +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +async fn refunds_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + connector_name: &str, + source_verified: bool, + event_type: webhooks::IncomingWebhookEvent, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let db = &*state.store; + //find refund by connector refund id + let refund = match webhook_details.object_reference_id { + webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { + webhooks::RefundIdType::RefundId(id) => db + .find_refund_by_merchant_id_refund_id( + &merchant_account.merchant_id, + &id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the refund")?, + webhooks::RefundIdType::ConnectorRefundId(id) => db + .find_refund_by_merchant_id_connector_refund_id_connector( + &merchant_account.merchant_id, + &id, + connector_name, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the refund")?, + }, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received a non-refund id when processing refund webhooks")?, + }; + let refund_id = refund.refund_id.to_owned(); + //if source verified then update refund status else trigger refund sync + let updated_refund = if source_verified { + let refund_update = storage::RefundUpdate::StatusUpdate { + connector_refund_id: None, + sent_to_gateway: true, + refund_status: common_enums::RefundStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed refund status mapping from event type")?, + updated_by: merchant_account.storage_scheme.to_string(), + }; + db.update_refund( + refund.to_owned(), + refund_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? + } else { + Box::pin(refunds::refund_retrieve_core( + state.clone(), + merchant_account.clone(), + key_store.clone(), + api_models::refunds::RefundsRetrieveRequest { + refund_id: refund_id.to_owned(), + force_sync: Some(true), + merchant_connector_details: None, + }, + )) + .await + .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? + }; + let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into(); + + // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook + if let Some(outgoing_event_type) = event_type { + let refund_response: api_models::refunds::RefundResponse = + updated_refund.clone().foreign_into(); + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Refunds, + refund_id, + enums::EventObjectType::RefundDetails, + api::OutgoingWebhookContent::RefundDetails(refund_response), + Some(updated_refund.created_at), + ) + .await?; + } + + Ok(WebhookResponseTracker::Refund { + payment_id: updated_refund.payment_id, + refund_id: updated_refund.refund_id, + status: updated_refund.refund_status, + }) +} + +async fn get_payment_attempt_from_object_reference_id( + state: &SessionState, + object_reference_id: webhooks::ObjectReferenceId, + merchant_account: &domain::MerchantAccount, +) -> CustomResult< + hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + errors::ApiErrorResponse, +> { + let db = &*state.store; + match object_reference_id { + api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db + .find_payment_attempt_by_merchant_id_connector_txn_id( + &merchant_account.merchant_id, + id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), + api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db + .find_payment_attempt_by_attempt_id_merchant_id( + id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), + api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db + .find_payment_attempt_by_preprocessing_id_merchant_id( + id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received a non-payment id for retrieving payment")?, + } +} + +#[allow(clippy::too_many_arguments)] +async fn get_or_update_dispute_object( + state: SessionState, + option_dispute: Option<diesel_models::dispute::Dispute>, + dispute_details: api::disputes::DisputePayload, + merchant_id: &str, + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + event_type: webhooks::IncomingWebhookEvent, + business_profile: &diesel_models::business_profile::BusinessProfile, + connector_name: &str, +) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { + let db = &*state.store; + match option_dispute { + None => { + metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); + let dispute_id = generate_id(consts::ID_LENGTH, "dp"); + let new_dispute = diesel_models::dispute::DisputeNew { + dispute_id, + amount: dispute_details.amount.clone(), + currency: dispute_details.currency, + dispute_stage: dispute_details.dispute_stage, + dispute_status: common_enums::DisputeStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event type to dispute status mapping failed")?, + payment_id: payment_attempt.payment_id.to_owned(), + connector: connector_name.to_owned(), + attempt_id: payment_attempt.attempt_id.to_owned(), + merchant_id: merchant_id.to_owned(), + connector_status: dispute_details.connector_status, + connector_dispute_id: dispute_details.connector_dispute_id, + connector_reason: dispute_details.connector_reason, + connector_reason_code: dispute_details.connector_reason_code, + challenge_required_by: dispute_details.challenge_required_by, + connector_created_at: dispute_details.created_at, + connector_updated_at: dispute_details.updated_at, + 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 + .insert_dispute(new_dispute.clone()) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + } + Some(dispute) => { + logger::info!("Dispute Already exists, Updating the dispute details"); + metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(&metrics::CONTEXT, 1, &[]); + let dispute_status = diesel_models::enums::DisputeStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event type to dispute state conversion failure")?; + crate::core::utils::validate_dispute_stage_and_dispute_status( + dispute.dispute_stage, + dispute.dispute_status, + dispute_details.dispute_stage, + dispute_status, + ) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("dispute stage and status validation failed")?; + let update_dispute = diesel_models::dispute::DisputeUpdate::Update { + dispute_stage: dispute_details.dispute_stage, + dispute_status, + connector_status: dispute_details.connector_status, + connector_reason: dispute_details.connector_reason, + connector_reason_code: dispute_details.connector_reason_code, + challenge_required_by: dispute_details.challenge_required_by, + connector_updated_at: dispute_details.updated_at, + }; + db.update_dispute(dispute, update_dispute) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + } + } +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +async fn external_authentication_incoming_webhook_flow( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + source_verified: bool, + event_type: webhooks::IncomingWebhookEvent, + request_details: &api::IncomingWebhookRequestDetails<'_>, + connector: &(dyn api::Connector + Sync), + object_ref_id: api::ObjectReferenceId, + business_profile: diesel_models::business_profile::BusinessProfile, + merchant_connector_account: domain::MerchantConnectorAccount, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + if source_verified { + let authentication_details = connector + .get_external_authentication_details(request_details) + .switch()?; + let trans_status = authentication_details.trans_status; + let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate { + authentication_status: common_enums::AuthenticationStatus::foreign_from( + trans_status.clone(), + ), + trans_status, + authentication_value: authentication_details.authentication_value, + eci: authentication_details.eci, + }; + let authentication = + if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) = + object_ref_id + { + match authentication_id_type { + webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state + .store + .find_authentication_by_merchant_id_authentication_id( + merchant_account.merchant_id.clone(), + authentication_id.clone(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { + id: authentication_id, + }) + .attach_printable("Error while fetching authentication record"), + webhooks::AuthenticationIdType::ConnectorAuthenticationId( + connector_authentication_id, + ) => state + .store + .find_authentication_by_merchant_id_connector_authentication_id( + merchant_account.merchant_id.clone(), + connector_authentication_id.clone(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { + id: connector_authentication_id, + }) + .attach_printable("Error while fetching authentication record"), + } + } else { + Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( + "received a non-external-authentication id for retrieving authentication", + ) + }?; + let updated_authentication = state + .store + .update_authentication_by_merchant_id_authentication_id( + authentication, + authentication_update, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while updating authentication")?; + // Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows + if let Some(payment_id) = updated_authentication.payment_id { + let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose())); + // Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook + if !is_pull_mechanism_enabled + && updated_authentication.authentication_type + == Some(common_enums::DecoupledAuthenticationType::Challenge) + && event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes + { + let payment_confirm_req = api::PaymentsRequest { + payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( + payment_id, + )), + merchant_id: Some(merchant_account.merchant_id.clone()), + ..Default::default() + }; + let payments_response = Box::pin(payments::payments_core::< + api::Authorize, + api::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + merchant_account.clone(), + key_store.clone(), + payments::PaymentConfirm, + payment_confirm_req, + services::api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), + )) + .await?; + match payments_response { + services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + let payment_id = payments_response + .payment_id + .clone() + .get_required_value("payment_id") + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment id not received from payments core")?; + let status = payments_response.status; + let event_type: Option<enums::EventType> = + payments_response.status.foreign_into(); + // Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client + let poll_id = core_utils::get_poll_id( + merchant_account.merchant_id.clone(), + core_utils::get_external_authentication_request_poll_id(&payment_id), + ); + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + redis_conn + .set_key_without_modifying_ttl( + &poll_id, + api_models::poll::PollStatus::Completed.to_string(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add poll_id in redis")?; + // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook + if let Some(outgoing_event_type) = event_type { + let primary_object_created_at = payments_response.created; + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Payments, + payment_id.clone(), + enums::EventObjectType::PaymentDetails, + api::OutgoingWebhookContent::PaymentDetails(payments_response), + primary_object_created_at, + ) + .await?; + }; + let response = WebhookResponseTracker::Payment { payment_id, status }; + Ok(response) + } + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( + "Did not get payment id as object reference id in webhook payments flow", + )?, + } + } else { + Ok(WebhookResponseTracker::NoEffect) + } + } else { + Ok(WebhookResponseTracker::NoEffect) + } + } else { + logger::error!( + "Webhook source verification failed for external authentication webhook flow" + ); + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + } +} + +#[instrument(skip_all)] +async fn mandates_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + source_verified: bool, + event_type: webhooks::IncomingWebhookEvent, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + if source_verified { + let db = &*state.store; + let mandate = match webhook_details.object_reference_id { + webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( + mandate_id, + )) => db + .find_mandate_by_merchant_id_mandate_id( + &merchant_account.merchant_id, + mandate_id.as_str(), + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, + webhooks::ObjectReferenceId::MandateId( + webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id), + ) => db + .find_mandate_by_merchant_id_connector_mandate_id( + &merchant_account.merchant_id, + connector_mandate_id.as_str(), + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received a non-mandate id for retrieving mandate")?, + }; + let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event type to mandate status mapping failed")?; + let mandate_id = mandate.mandate_id.clone(); + let updated_mandate = db + .update_mandate_by_merchant_id_mandate_id( + &merchant_account.merchant_id, + &mandate_id, + storage::MandateUpdate::StatusUpdate { mandate_status }, + mandate, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + let mandates_response = Box::new( + api::mandates::MandateResponse::from_db_mandate( + &state, + key_store.clone(), + updated_mandate.clone(), + merchant_account.storage_scheme, + ) + .await?, + ); + let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); + if let Some(outgoing_event_type) = event_type { + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Mandates, + updated_mandate.mandate_id.clone(), + enums::EventObjectType::MandateDetails, + api::OutgoingWebhookContent::MandateDetails(mandates_response), + Some(updated_mandate.created_at), + ) + .await?; + } + Ok(WebhookResponseTracker::Mandate { + mandate_id: updated_mandate.mandate_id, + status: updated_mandate.mandate_status, + }) + } else { + logger::error!("Webhook source verification failed for mandates webhook flow"); + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + } +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +async fn frm_incoming_webhook_flow( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + source_verified: bool, + event_type: webhooks::IncomingWebhookEvent, + object_ref_id: api::ObjectReferenceId, + business_profile: diesel_models::business_profile::BusinessProfile, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + if source_verified { + let payment_attempt = + get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) + .await?; + let payment_response = match event_type { + webhooks::IncomingWebhookEvent::FrmApproved => { + Box::pin(payments::payments_core::< + api::Capture, + api::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + merchant_account.clone(), + key_store.clone(), + payments::PaymentApprove, + api::PaymentsCaptureRequest { + payment_id: payment_attempt.payment_id, + amount_to_capture: payment_attempt.amount_to_capture, + ..Default::default() + }, + services::api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::default(), + )) + .await? + } + webhooks::IncomingWebhookEvent::FrmRejected => { + Box::pin(payments::payments_core::< + api::Void, + api::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + merchant_account.clone(), + key_store.clone(), + payments::PaymentReject, + api::PaymentsCancelRequest { + payment_id: payment_attempt.payment_id.clone(), + cancellation_reason: Some( + "Rejected by merchant based on FRM decision".to_string(), + ), + ..Default::default() + }, + services::api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::default(), + )) + .await? + } + _ => Err(errors::ApiErrorResponse::EventNotFound)?, + }; + match payment_response { + services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + let payment_id = payments_response + .payment_id + .clone() + .get_required_value("payment_id") + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment id not received from payments core")?; + let status = payments_response.status; + let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + if let Some(outgoing_event_type) = event_type { + let primary_object_created_at = payments_response.created; + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Payments, + payment_id.clone(), + enums::EventObjectType::PaymentDetails, + api::OutgoingWebhookContent::PaymentDetails(payments_response), + primary_object_created_at, + ) + .await?; + }; + let response = WebhookResponseTracker::Payment { payment_id, status }; + Ok(response) + } + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( + "Did not get payment id as object reference id in webhook payments flow", + )?, + } + } else { + logger::error!("Webhook source verification failed for frm webhooks flow"); + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + } +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +async fn disputes_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + source_verified: bool, + connector: &(dyn api::Connector + Sync), + request_details: &api::IncomingWebhookRequestDetails<'_>, + event_type: webhooks::IncomingWebhookEvent, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); + if source_verified { + let db = &*state.store; + let dispute_details = connector.get_dispute_details(request_details).switch()?; + let payment_attempt = get_payment_attempt_from_object_reference_id( + &state, + webhook_details.object_reference_id, + &merchant_account, + ) + .await?; + let option_dispute = db + .find_by_merchant_id_payment_id_connector_dispute_id( + &merchant_account.merchant_id, + &payment_attempt.payment_id, + &dispute_details.connector_dispute_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?; + let dispute_object = get_or_update_dispute_object( + state.clone(), + option_dispute, + dispute_details, + &merchant_account.merchant_id, + &payment_attempt, + event_type, + &business_profile, + connector.id(), + ) + .await?; + let disputes_response = Box::new(dispute_object.clone().foreign_into()); + let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); + + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + event_type, + enums::EventClass::Disputes, + dispute_object.dispute_id.clone(), + enums::EventObjectType::DisputeDetails, + api::OutgoingWebhookContent::DisputeDetails(disputes_response), + Some(dispute_object.created_at), + ) + .await?; + metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(&metrics::CONTEXT, 1, &[]); + Ok(WebhookResponseTracker::Dispute { + dispute_id: dispute_object.dispute_id, + payment_id: dispute_object.payment_id, + status: dispute_object.dispute_status, + }) + } else { + metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + } +} + +#[instrument(skip_all)] +async fn bank_transfer_webhook_flow( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + source_verified: bool, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let response = if source_verified { + let payment_attempt = get_payment_attempt_from_object_reference_id( + &state, + webhook_details.object_reference_id, + &merchant_account, + ) + .await?; + let payment_id = payment_attempt.payment_id; + let request = api::PaymentsRequest { + payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( + payment_id, + )), + payment_token: payment_attempt.payment_token, + ..Default::default() + }; + Box::pin(payments::payments_core::< + api::Authorize, + api::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + merchant_account.to_owned(), + key_store.clone(), + payments::PaymentConfirm, + request, + services::api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::with_source(common_enums::PaymentSource::Webhook), + )) + .await + } else { + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + }; + + match response? { + services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { + let payment_id = payments_response + .payment_id + .clone() + .get_required_value("payment_id") + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("did not receive payment id from payments core response")?; + + let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + let status = payments_response.status; + + // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook + if let Some(outgoing_event_type) = event_type { + let primary_object_created_at = payments_response.created; + super::create_event_and_trigger_outgoing_webhook( + state, + merchant_account, + business_profile, + &key_store, + outgoing_event_type, + enums::EventClass::Payments, + payment_id.clone(), + enums::EventObjectType::PaymentDetails, + api::OutgoingWebhookContent::PaymentDetails(payments_response), + primary_object_created_at, + ) + .await?; + } + + Ok(WebhookResponseTracker::Payment { payment_id, status }) + } + + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received non-json response from payments core")?, + } +} + +#[inline] +async fn get_payment_id( + db: &dyn StorageInterface, + payment_id: &api::PaymentIdType, + merchant_id: &str, + storage_scheme: enums::MerchantStorageScheme, +) -> errors::RouterResult<String> { + let pay_id = || async { + match payment_id { + api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_string()), + api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db + .find_payment_attempt_by_merchant_id_connector_txn_id( + merchant_id, + id, + storage_scheme, + ) + .await + .map(|p| p.payment_id), + api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db + .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) + .await + .map(|p| p.payment_id), + api_models::payments::PaymentIdType::PreprocessingId(ref id) => db + .find_payment_attempt_by_preprocessing_id_merchant_id( + id, + merchant_id, + storage_scheme, + ) + .await + .map(|p| p.payment_id), + } + }; + + pay_id() + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) +} + +fn get_connector_by_connector_name( + state: &SessionState, + connector_name: &str, + merchant_connector_id: Option<String>, +) -> CustomResult<(&'static (dyn api::Connector + Sync), String), errors::ApiErrorResponse> { + let authentication_connector = + api_models::enums::convert_authentication_connector(connector_name); + #[cfg(feature = "frm")] + { + let frm_connector = api_models::enums::convert_frm_connector(connector_name); + if frm_connector.is_some() { + let frm_connector_data = + api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; + return Ok(( + *frm_connector_data.connector, + frm_connector_data.connector_name.to_string(), + )); + } + } + + let (connector, connector_name) = if authentication_connector.is_some() { + let authentication_connector_data = + api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; + ( + authentication_connector_data.connector, + authentication_connector_data.connector_name.to_string(), + ) + } else { + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + connector_name, + api::GetToken::Connector, + merchant_connector_id, + ) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "invalid connector name received".to_string(), + }) + .attach_printable("Failed construction of ConnectorData")?; + ( + connector_data.connector, + connector_data.connector_name.to_string(), + ) + }; + Ok((*connector, connector_name)) +} + +/// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id}) +/// if merchant connector id is not passed in the request, then this will return None for mca +async fn fetch_optional_mca_and_connector( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + connector_name_or_mca_id: &str, + key_store: &domain::MerchantKeyStore, +) -> CustomResult< + ( + Option<domain::MerchantConnectorAccount>, + &'static (dyn api::Connector + Sync), + String, + ), + errors::ApiErrorResponse, +> { + let db = &state.store; + if connector_name_or_mca_id.starts_with("mca_") { + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &merchant_account.merchant_id, + connector_name_or_mca_id, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_name_or_mca_id.to_string(), + }) + .attach_printable( + "error while fetching merchant_connector_account from connector_id", + )?; + let (connector, connector_name) = get_connector_by_connector_name( + state, + &mca.connector_name, + Some(mca.merchant_connector_id.clone()), + )?; + + Ok((Some(mca), connector, connector_name)) + } else { + // Merchant connector account is already being queried, it is safe to set connector id as None + let (connector, connector_name) = + get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; + Ok((None, connector, connector_name)) + } +} diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs new file mode 100644 index 00000000000..94f96c45216 --- /dev/null +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -0,0 +1,775 @@ +use api_models::{ + webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, + webhooks, +}; +use common_utils::{ext_traits::Encode, request::RequestContent}; +use error_stack::{report, ResultExt}; +use masking::{ExposeInterface, Mask, PeekInterface, Secret}; +use router_env::{ + instrument, + tracing::{self, Instrument}, +}; + +use super::{types, utils, MERCHANT_ID}; +#[cfg(feature = "stripe")] +use crate::compatibility::stripe::webhooks as stripe_webhooks; +use crate::{ + core::{ + errors::{self, CustomResult}, + metrics, + }, + db::StorageInterface, + events::outgoing_webhook_logs::{OutgoingWebhookEvent, OutgoingWebhookEventMetric}, + logger, + routes::{app::SessionStateInfo, metrics::request::add_attributes, SessionState}, + services, + types::{ + api, + domain::{self, types as domain_types}, + storage::{self, enums}, + }, + utils::{OptionExt, ValueExt}, + workflows::outgoing_webhook_retry, +}; + +const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub(crate) async fn create_event_and_trigger_outgoing_webhook( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: diesel_models::business_profile::BusinessProfile, + merchant_key_store: &domain::MerchantKeyStore, + event_type: enums::EventType, + event_class: enums::EventClass, + primary_object_id: String, + primary_object_type: enums::EventObjectType, + content: api::OutgoingWebhookContent, + primary_object_created_at: Option<time::PrimitiveDateTime>, +) -> CustomResult<(), errors::ApiErrorResponse> { + let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt; + let idempotent_event_id = + utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt); + let webhook_url_result = get_webhook_url_from_business_profile(&business_profile); + + if !state.conf.webhooks.outgoing_enabled + || webhook_url_result.is_err() + || webhook_url_result.as_ref().is_ok_and(String::is_empty) + { + logger::debug!( + business_profile_id=%business_profile.profile_id, + %idempotent_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 event_id = utils::generate_event_id(); + let merchant_id = business_profile.merchant_id.clone(); + let now = common_utils::date_time::now(); + + let outgoing_webhook = api::OutgoingWebhook { + merchant_id: merchant_id.clone(), + event_id: event_id.clone(), + event_type, + content: content.clone(), + timestamp: now, + }; + + let request_content = get_outgoing_webhook_request( + &merchant_account, + outgoing_webhook, + business_profile.payment_response_hash_key.as_deref(), + ) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to construct outgoing webhook request content")?; + + let new_event = domain::Event { + event_id: event_id.clone(), + event_type, + event_class, + is_webhook_notified: false, + primary_object_id, + primary_object_type, + created_at: now, + merchant_id: Some(business_profile.merchant_id.clone()), + business_profile_id: Some(business_profile.profile_id.clone()), + primary_object_created_at, + idempotent_event_id: Some(idempotent_event_id.clone()), + initial_attempt_id: Some(event_id.clone()), + request: Some( + domain_types::encrypt( + request_content + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to encode outgoing webhook request content") + .map(Secret::new)?, + merchant_key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to encrypt outgoing webhook request content")?, + ), + response: None, + delivery_attempt: Some(delivery_attempt), + }; + + let event_insert_result = state + .store + .insert_event(new_event, merchant_key_store) + .await; + + let event = match event_insert_result { + Ok(event) => Ok(event), + Err(error) => { + if error.current_context().is_db_unique_violation() { + logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database"); + return Ok(()); + } else { + logger::error!(event_insertion_failure=?error); + Err(error + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to insert event in events table")) + } + } + }?; + + 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 cloned_key_store = merchant_key_store.clone(); + // Using a tokio spawn here and not arbiter because not all caller of this function + // may have an actix arbiter + tokio::spawn( + async move { + Box::pin(trigger_webhook_and_raise_event( + state, + business_profile, + &cloned_key_store, + event, + request_content, + delivery_attempt, + Some(content), + process_tracker, + )) + .await; + } + .in_current_span(), + ); + + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub(crate) async fn trigger_webhook_and_raise_event( + state: SessionState, + business_profile: diesel_models::business_profile::BusinessProfile, + merchant_key_store: &domain::MerchantKeyStore, + event: domain::Event, + request_content: OutgoingWebhookRequestContent, + delivery_attempt: enums::WebhookDeliveryAttempt, + content: Option<api::OutgoingWebhookContent>, + process_tracker: Option<storage::ProcessTracker>, +) { + logger::debug!( + event_id=%event.event_id, + idempotent_event_id=?event.idempotent_event_id, + initial_attempt_id=?event.initial_attempt_id, + "Attempting to send webhook" + ); + + let merchant_id = business_profile.merchant_id.clone(); + let trigger_webhook_result = trigger_webhook_to_merchant( + state.clone(), + business_profile, + merchant_key_store, + event.clone(), + request_content, + delivery_attempt, + process_tracker, + ) + .await; + + raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event); +} + +async fn trigger_webhook_to_merchant( + state: SessionState, + business_profile: diesel_models::business_profile::BusinessProfile, + merchant_key_store: &domain::MerchantKeyStore, + event: domain::Event, + request_content: OutgoingWebhookRequestContent, + delivery_attempt: enums::WebhookDeliveryAttempt, + process_tracker: Option<storage::ProcessTracker>, +) -> CustomResult<(), errors::WebhooksFlowError> { + 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 event_id = event.event_id; + + let headers = request_content + .headers + .into_iter() + .map(|(name, value)| (name, value.into_masked())) + .collect(); + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&webhook_url) + .attach_default_headers() + .headers(headers) + .set_body(RequestContent::RawBytes( + request_content.body.expose().into_bytes(), + )) + .build(); + + let response = state + .api_client + .send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false) + .await; + + metrics::WEBHOOK_OUTGOING_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new( + MERCHANT_ID, + business_profile.merchant_id.clone(), + )], + ); + logger::debug!(outgoing_webhook_response=?response); + + let update_event_if_client_error = + |state: SessionState, + merchant_key_store: domain::MerchantKeyStore, + merchant_id: String, + event_id: String, + error_message: String| async move { + let is_webhook_notified = false; + + let response_to_store = OutgoingWebhookResponseContent { + body: None, + headers: None, + status_code: None, + error_message: Some(error_message), + }; + + let event_update = domain::EventUpdate::UpdateResponse { + is_webhook_notified, + response: Some( + domain_types::encrypt( + response_to_store + .encode_to_string_of_json() + .change_context( + errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, + ) + .map(Secret::new)?, + merchant_key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) + .attach_printable("Failed to encrypt outgoing webhook response content")?, + ), + }; + + state + .store + .update_event_by_merchant_id_event_id( + &merchant_id, + &event_id, + event_update, + &merchant_key_store, + ) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) + }; + + let api_client_error_handler = + |state: SessionState, + merchant_key_store: domain::MerchantKeyStore, + merchant_id: String, + event_id: String, + client_error: error_stack::Report<errors::ApiClientError>, + delivery_attempt: enums::WebhookDeliveryAttempt| async move { + // Not including detailed error message in response information since it contains too + // much of diagnostic information to be exposed to the merchant. + update_event_if_client_error( + state, + merchant_key_store, + merchant_id, + event_id, + "Unable to send request to merchant server".to_string(), + ) + .await?; + + let error = + client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed); + logger::error!( + ?error, + ?delivery_attempt, + "An error occurred when sending webhook to merchant" + ); + + Ok::<_, error_stack::Report<errors::WebhooksFlowError>>(()) + }; + let update_event_in_storage = |state: SessionState, + merchant_key_store: domain::MerchantKeyStore, + merchant_id: String, + event_id: String, + response: reqwest::Response| async move { + let status_code = response.status(); + let is_webhook_notified = status_code.is_success(); + + let response_headers = response + .headers() + .iter() + .map(|(name, value)| { + ( + name.as_str().to_owned(), + value + .to_str() + .map(|s| Secret::from(String::from(s))) + .unwrap_or_else(|error| { + logger::warn!( + "Response header {} contains non-UTF-8 characters: {error:?}", + name.as_str() + ); + Secret::from(String::from("Non-UTF-8 header value")) + }), + ) + }) + .collect::<Vec<_>>(); + let response_body = response + .text() + .await + .map(Secret::from) + .unwrap_or_else(|error| { + logger::warn!("Response contains non-UTF-8 characters: {error:?}"); + Secret::from(String::from("Non-UTF-8 response body")) + }); + let response_to_store = OutgoingWebhookResponseContent { + body: Some(response_body), + headers: Some(response_headers), + status_code: Some(status_code.as_u16()), + error_message: None, + }; + + let event_update = domain::EventUpdate::UpdateResponse { + is_webhook_notified, + response: Some( + domain_types::encrypt( + response_to_store + .encode_to_string_of_json() + .change_context( + errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, + ) + .map(Secret::new)?, + merchant_key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) + .attach_printable("Failed to encrypt outgoing webhook response content")?, + ), + }; + state + .store + .update_event_by_merchant_id_event_id( + &merchant_id, + &event_id, + event_update, + &merchant_key_store, + ) + .await + .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) + }; + let increment_webhook_outgoing_received_count = |merchant_id: String| { + metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::KeyValue::new(MERCHANT_ID, merchant_id)], + ) + }; + let success_response_handler = + |state: SessionState, + merchant_id: String, + process_tracker: Option<storage::ProcessTracker>, + business_status: &'static str| async move { + increment_webhook_outgoing_received_count(merchant_id); + + match process_tracker { + Some(process_tracker) => state + .store + .as_scheduler() + .finish_process_with_business_status(process_tracker, business_status.into()) + .await + .change_context( + errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, + ), + None => Ok(()), + } + }; + let error_response_handler = |merchant_id: String, + delivery_attempt: enums::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 { + enums::WebhookDeliveryAttempt::InitialAttempt => match response { + Err(client_error) => { + api_client_error_handler( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + client_error, + delivery_attempt, + ) + .await? + } + Ok(response) => { + let status_code = response.status(); + let _updated_event = update_event_in_storage( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + response, + ) + .await?; + + if status_code.is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + process_tracker, + "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id, + delivery_attempt, + status_code.as_u16(), + "Ignoring error when sending webhook to merchant", + ); + } + } + }, + enums::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( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + client_error, + delivery_attempt, + ) + .await?; + // 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) => { + let status_code = response.status(); + let _updated_event = update_event_in_storage( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + response, + ) + .await?; + + if status_code.is_success() { + success_response_handler( + state.clone(), + business_profile.merchant_id, + Some(process_tracker), + "COMPLETED_BY_PT", + ) + .await?; + } else { + error_response_handler( + business_profile.merchant_id.clone(), + delivery_attempt, + status_code.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, + )?; + } + } + } + } + enums::WebhookDeliveryAttempt::ManualRetry => match response { + Err(client_error) => { + api_client_error_handler( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + client_error, + delivery_attempt, + ) + .await? + } + Ok(response) => { + let status_code = response.status(); + let _updated_event = update_event_in_storage( + state.clone(), + merchant_key_store.clone(), + business_profile.merchant_id.clone(), + event_id.clone(), + response, + ) + .await?; + + if status_code.is_success() { + increment_webhook_outgoing_received_count(business_profile.merchant_id.clone()); + } else { + error_response_handler( + business_profile.merchant_id, + delivery_attempt, + status_code.as_u16(), + "Ignoring error when sending webhook to merchant", + ); + } + } + }, + } + + Ok(()) +} + +fn raise_webhooks_analytics_event( + state: SessionState, + trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, + content: Option<api::OutgoingWebhookContent>, + merchant_id: String, + event: domain::Event, +) { + 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()) + .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 + .as_ref() + .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content); + let webhook_event = OutgoingWebhookEvent::new( + merchant_id, + event.event_id, + event.event_type, + outgoing_webhook_event_content, + error, + event.initial_attempt_id, + ); + state.event_handler().log_event(&webhook_event); +} + +pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( + db: &dyn StorageInterface, + business_profile: &diesel_models::business_profile::BusinessProfile, + event: &domain::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 + )) + .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, + initial_attempt_id: event.initial_attempt_id.clone(), + }; + + 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.event_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) + } + } +} + +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) +} + +pub(crate) fn get_outgoing_webhook_request( + merchant_account: &domain::MerchantAccount, + outgoing_webhook: api::OutgoingWebhook, + payment_response_hash_key: Option<&str>, +) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { + #[inline] + fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>( + outgoing_webhook: api::OutgoingWebhook, + payment_response_hash_key: Option<&str>, + ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { + let mut headers = vec![( + reqwest::header::CONTENT_TYPE.to_string(), + mime::APPLICATION_JSON.essence_str().into(), + )]; + + let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook); + + let outgoing_webhooks_signature = transformed_outgoing_webhook + .get_outgoing_webhooks_signature(payment_response_hash_key)?; + + if let Some(signature) = outgoing_webhooks_signature.signature { + WebhookType::add_webhook_header(&mut headers, signature) + } + + Ok(OutgoingWebhookRequestContent { + body: outgoing_webhooks_signature.payload, + headers: headers + .into_iter() + .map(|(name, value)| (name, Secret::new(value.into_inner()))) + .collect(), + }) + } + + match merchant_account.get_compatible_connector() { + #[cfg(feature = "stripe")] + Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::< + stripe_webhooks::StripeOutgoingWebhook, + >( + outgoing_webhook, payment_response_hash_key + ), + _ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( + outgoing_webhook, + payment_response_hash_key, + ), + } +} diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs index 2cb16a53b3a..c5ba557a78d 100644 --- a/crates/router/src/core/webhooks/webhook_events.rs +++ b/crates/router/src/core/webhooks/webhook_events.rs @@ -231,7 +231,7 @@ pub async fn retry_delivery_attempt( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event request information")?; - Box::pin(super::trigger_webhook_and_raise_event( + Box::pin(super::outgoing::trigger_webhook_and_raise_event( state.clone(), business_profile, &key_store, diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index fee38dbacd2..a198fe730fe 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -26,7 +26,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( &req, (), |state, auth, _, req_state| { - webhooks::webhooks_wrapper::<W>( + webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state,
refactor
extract incoming and outgoing webhooks into separate modules (#4870)
fa09db1534884037947c6d488e33a3ce600c2a0c
2025-02-12 13:18:38
Kashif
refactor(schema): add a new column for storing large connector transaction IDs (#7017)
false
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4e88d5c0fde..0377a3e8183 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1420,7 +1420,7 @@ crate::impl_to_sql_from_sql_json!(BrowserInformation); /// In case connector's use an identifier whose length exceeds 128 characters, /// the hash value of such identifiers will be stored as connector_transaction_id. /// The actual connector's identifier will be stored in a separate column - -/// connector_transaction_data or something with a similar name. +/// processor_transaction_data or something with a similar name. #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub enum ConnectorTransactionId { @@ -1438,7 +1438,7 @@ impl ConnectorTransactionId { } } - /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and connector_transaction_data + /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and processor_transaction_data pub fn form_id_and_data(src: String) -> (Self, Option<String>) { let txn_id = Self::from(src.clone()); match txn_id { @@ -1456,10 +1456,10 @@ impl ConnectorTransactionId { (Self::TxnId(id), _) => Ok(id), (Self::HashedData(_), Some(id)) => Ok(id), (Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue { - message: "connector_transaction_data is empty for HashedData variant".to_string(), + message: "processor_transaction_data is empty for HashedData variant".to_string(), }) .attach_printable(format!( - "connector_transaction_data is empty for connector_transaction_id {}", + "processor_transaction_data is empty for connector_transaction_id {}", id ))), } diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs index d6272c34060..367382b98bf 100644 --- a/crates/diesel_models/src/capture.rs +++ b/crates/diesel_models/src/capture.rs @@ -30,7 +30,9 @@ pub struct Capture { pub capture_sequence: i16, // reference to the capture at connector side pub connector_response_reference_id: Option<String>, + /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] @@ -55,7 +57,9 @@ pub struct CaptureNew { pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, pub connector_response_reference_id: Option<String>, + /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -64,7 +68,7 @@ pub enum CaptureUpdate { status: storage_enums::CaptureStatus, connector_capture_id: Option<ConnectorTransactionId>, connector_response_reference_id: Option<String>, - connector_capture_data: Option<String>, + processor_capture_data: Option<String>, }, ErrorUpdate { status: storage_enums::CaptureStatus, @@ -84,7 +88,7 @@ pub struct CaptureUpdateInternal { pub modified_at: Option<PrimitiveDateTime>, pub connector_capture_id: Option<ConnectorTransactionId>, pub connector_response_reference_id: Option<String>, - pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } impl CaptureUpdate { @@ -97,7 +101,7 @@ impl CaptureUpdate { modified_at: _, connector_capture_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, } = self.into(); Capture { status: status.unwrap_or(source.status), @@ -108,7 +112,7 @@ impl CaptureUpdate { connector_capture_id: connector_capture_id.or(source.connector_capture_id), connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), - connector_capture_data: connector_capture_data.or(source.connector_capture_data), + processor_capture_data: processor_capture_data.or(source.processor_capture_data), ..source } } @@ -122,13 +126,13 @@ impl From<CaptureUpdate> for CaptureUpdateInternal { status, connector_capture_id: connector_transaction_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, } => Self { status: Some(status), connector_capture_id: connector_transaction_id, modified_at: now, connector_response_reference_id, - connector_capture_data, + processor_capture_data, ..Self::default() }, CaptureUpdate::ErrorUpdate { diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 94dcf00f755..54e60891532 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -227,7 +227,7 @@ pub enum Insertable { pub enum Updateable { PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), - RefundUpdate(RefundUpdateMems), + RefundUpdate(Box<RefundUpdateMems>), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index eab95f81316..b3b3f44f3c9 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -171,8 +171,10 @@ pub struct PaymentAttempt { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, + pub processor_transaction_data: Option<String>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, } @@ -183,7 +185,7 @@ impl ConnectorTransactionIdTrait for PaymentAttempt { match self .connector_transaction_id .as_ref() - .map(|txn_id| txn_id.get_txn_id(self.connector_transaction_data.as_ref())) + .map(|txn_id| txn_id.get_txn_id(self.processor_transaction_data.as_ref())) .transpose() { Ok(txn_id) => txn_id, @@ -871,8 +873,8 @@ pub struct PaymentAttemptUpdateInternal { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, - pub connector_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, + pub processor_transaction_data: Option<String>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, } @@ -1055,7 +1057,7 @@ impl PaymentAttemptUpdate { card_network, shipping_cost, order_tax_amount, - connector_transaction_data, + processor_transaction_data, connector_mandate_detail, card_discovery, charges, @@ -1113,8 +1115,8 @@ impl PaymentAttemptUpdate { card_network: card_network.or(source.card_network), shipping_cost: shipping_cost.or(source.shipping_cost), order_tax_amount: order_tax_amount.or(source.order_tax_amount), - connector_transaction_data: connector_transaction_data - .or(source.connector_transaction_data), + processor_transaction_data: processor_transaction_data + .or(source.processor_transaction_data), connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), card_discovery: card_discovery.or(source.card_discovery), charges: charges.or(source.charges), @@ -1483,7 +1485,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { // card_network: None, // shipping_cost: None, // order_tax_amount: None, - // connector_transaction_data: None, + // processor_transaction_data: None, // connector_mandate_detail, // }, // PaymentAttemptUpdate::ConnectorMandateDetailUpdate { @@ -2167,7 +2169,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2224,7 +2226,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2313,7 +2315,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost, order_tax_amount, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail, card_discovery, charges: None, @@ -2371,7 +2373,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2430,7 +2432,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2489,7 +2491,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2546,7 +2548,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail, card_discovery: None, charges: None, @@ -2603,7 +2605,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2631,7 +2633,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, charges, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2657,7 +2659,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code, unified_message, payment_method_data, - connector_transaction_data, + processor_transaction_data, + connector_mandate_detail, + charges, amount: None, net_amount: None, currency: None, @@ -2686,9 +2690,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_mandate_detail, card_discovery: None, - charges, } } PaymentAttemptUpdate::ErrorUpdate { @@ -2705,7 +2707,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_data, authentication_type, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2724,7 +2726,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, payment_method_data, authentication_type, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -2814,7 +2816,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2877,7 +2879,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2893,7 +2895,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_response_reference_id, updated_by, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2909,7 +2911,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { error_reason, connector_response_reference_id, updated_by, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -2962,7 +2964,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_response_reference_id, updated_by, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2976,7 +2978,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, connector_response_reference_id, updated_by, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -3075,7 +3077,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3133,7 +3135,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3146,7 +3148,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, charges, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -3158,7 +3160,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector: connector.map(Some), modified_at: common_utils::date_time::now(), updated_by, - connector_transaction_data, + processor_transaction_data, + charges, amount: None, net_amount: None, currency: None, @@ -3203,7 +3206,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, - charges, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { @@ -3258,7 +3260,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3318,7 +3320,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3333,7 +3335,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_message, connector_transaction_id, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -3348,7 +3350,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code: unified_code.map(Some), unified_message: unified_message.map(Some), connector_transaction_id, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -3445,7 +3447,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs index 7a32e410961..3f02948d2a4 100644 --- a/crates/diesel_models/src/query/capture.rs +++ b/crates/diesel_models/src/query/capture.rs @@ -74,7 +74,7 @@ impl ConnectorTransactionIdTrait for Capture { match self .connector_capture_id .as_ref() - .map(|capture_id| capture_id.get_txn_id(self.connector_capture_data.as_ref())) + .map(|capture_id| capture_id.get_txn_id(self.processor_capture_data.as_ref())) .transpose() { Ok(capture_id) => capture_id, diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index b929481d64d..f19c3252c60 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -51,11 +51,15 @@ pub struct Refund { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, + /// INFO: This field is deprecated and replaced by processor_refund_data pub connector_refund_data: Option<String>, + /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, } #[derive( @@ -99,9 +103,9 @@ pub struct RefundNew { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, - pub connector_refund_data: Option<String>, - pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -113,7 +117,7 @@ pub enum RefundUpdate { refund_error_message: Option<String>, refund_arn: String, updated_by: String, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, @@ -125,7 +129,7 @@ pub enum RefundUpdate { sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, @@ -133,7 +137,7 @@ pub enum RefundUpdate { refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, }, @@ -158,7 +162,7 @@ pub struct RefundUpdateInternal { refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, } @@ -176,7 +180,7 @@ impl RefundUpdateInternal { refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, - connector_refund_data: self.connector_refund_data, + processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source @@ -194,7 +198,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn, updated_by, - connector_refund_data, + processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), @@ -202,7 +206,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn: Some(refund_arn), updated_by, - connector_refund_data, + processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, @@ -225,7 +229,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }, @@ -234,13 +238,13 @@ impl From<RefundUpdate> for RefundUpdateInternal { sent_to_gateway, refund_status, updated_by, - connector_refund_data, + processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, - connector_refund_data, + processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, @@ -258,14 +262,14 @@ impl From<RefundUpdate> for RefundUpdateInternal { unified_message, updated_by, connector_refund_id, - connector_refund_data, + processor_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, - connector_refund_data, + processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, @@ -290,7 +294,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }, @@ -311,7 +315,7 @@ impl RefundUpdate { refund_error_code, updated_by, modified_at: _, - connector_refund_data, + processor_refund_data, unified_code, unified_message, } = self.into(); @@ -326,7 +330,7 @@ impl RefundUpdate { refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), - connector_refund_data: connector_refund_data.or(source.connector_refund_data), + processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), ..source @@ -340,7 +344,7 @@ pub struct RefundCoreWorkflow { pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, - pub connector_transaction_data: Option<String>, + pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] @@ -358,7 +362,7 @@ impl ConnectorTransactionIdTrait for Refund { match self .connector_refund_id .as_ref() - .map(|refund_id| refund_id.get_txn_id(self.connector_refund_data.as_ref())) + .map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref())) .transpose() { Ok(refund_id) => refund_id, @@ -374,7 +378,7 @@ impl ConnectorTransactionIdTrait for Refund { fn get_connector_transaction_id(&self) -> &String { match self .connector_transaction_id - .get_txn_id(self.connector_transaction_data.as_ref()) + .get_txn_id(self.processor_transaction_data.as_ref()) { Ok(txn_id) => txn_id, @@ -418,6 +422,7 @@ mod tests { "connector_transaction_data": null "unified_code": null, "unified_message": null, + "processor_transaction_data": null, }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index bbde92ea040..2e8219c5ab4 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -271,6 +271,7 @@ diesel::table! { connector_response_reference_id -> Nullable<Varchar>, #[max_length = 512] connector_capture_data -> Nullable<Varchar>, + processor_capture_data -> Nullable<Text>, } } @@ -909,6 +910,7 @@ diesel::table! { #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, connector_mandate_detail -> Nullable<Jsonb>, + processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, } @@ -1261,6 +1263,8 @@ diesel::table! { unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + processor_refund_data -> Nullable<Text>, + processor_transaction_data -> Nullable<Text>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index d17d4f8478a..ab2195526f5 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -278,8 +278,7 @@ diesel::table! { capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, - #[max_length = 512] - connector_capture_data -> Nullable<Varchar>, + processor_capture_data -> Nullable<Text>, } } @@ -872,8 +871,7 @@ diesel::table! { tax_on_surcharge -> Nullable<Int8>, payment_method_billing_address -> Nullable<Bytea>, redirection_data -> Nullable<Jsonb>, - #[max_length = 512] - connector_payment_data -> Nullable<Varchar>, + connector_payment_data -> Nullable<Text>, connector_token_details -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, @@ -1198,15 +1196,13 @@ diesel::table! { charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, - #[max_length = 512] - connector_refund_data -> Nullable<Varchar>, - #[max_length = 512] - connector_transaction_data -> Nullable<Varchar>, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + processor_refund_data -> Nullable<Text>, + processor_transaction_data -> Nullable<Text>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index c063545d81f..27085424083 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -201,7 +201,7 @@ pub struct PaymentAttemptBatchNew { pub organization_id: common_utils::id_type::OrganizationId, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, - pub connector_transaction_data: Option<String>, + pub processor_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub card_discovery: Option<common_enums::CardDiscovery>, } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs index 6e19c20edab..a43ffb7cfa1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs @@ -149,14 +149,12 @@ pub struct ExpiryDate { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { - #[serde(skip_serializing_if = "Option::is_none")] - pub address1: Option<Secret<String>>, + pub address1: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub address2: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub address3: Option<Secret<String>>, - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option<String>, + pub city: String, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<Secret<String>>, pub postal_code: Secret<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 28cbca418a3..65c884601de 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -90,10 +90,16 @@ fn fetch_payment_instrument( billing_address.and_then(|addr| addr.address.clone()) { Some(BillingAddress { - address1: address.line1, + address1: address.line1.get_required_value("line1").change_context( + errors::ConnectorError::MissingRequiredField { + field_name: "line1", + }, + )?, address2: address.line2, address3: address.line3, - city: address.city, + city: address.city.get_required_value("city").change_context( + errors::ConnectorError::MissingRequiredField { field_name: "city" }, + )?, state: address.state, postal_code: address.zip.get_required_value("zip").change_context( errors::ConnectorError::MissingRequiredField { field_name: "zip" }, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index e641ee63d27..133d04ceb69 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1512,7 +1512,7 @@ impl behaviour::Conversion for PaymentAttempt { .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); - let (connector_transaction_id, connector_transaction_data) = self + let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -1579,12 +1579,14 @@ impl behaviour::Conversion for PaymentAttempt { profile_id: self.profile_id, organization_id: self.organization_id, card_network, - connector_transaction_data, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), connector_mandate_detail: self.connector_mandate_detail, + processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + // Below fields are deprecated. Please add any new fields above this line. + connector_transaction_data: None, }) } diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index c5b9b9a0430..a9f5ae59493 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -13514,5 +13514,14 @@ pub fn get_worldpay_billing_required_fields() -> HashMap<String, RequiredFieldIn value: None, }, ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + }, + ), ]) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 4616be81a5f..25ae8c84c39 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1663,7 +1663,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .multiple_capture_data { Some(multiple_capture_data) => { - let (connector_capture_id, connector_capture_data) = + let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::NoResponseId => (None, None), types::ResponseId::ConnectorTransactionId(id) @@ -1679,7 +1679,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( )?, connector_capture_id: connector_capture_id.clone(), connector_response_reference_id, - connector_capture_data: connector_capture_data.clone(), + processor_capture_data: processor_capture_data.clone(), }; let capture_update_list = vec![( multiple_capture_data.get_latest_capture().clone(), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 1f6e03a0dec..ebf837792dc 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3847,7 +3847,7 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { connector_response_reference_id, .. } => { - let (connector_capture_id, connector_capture_data) = match resource_id { + let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => { (None, None) } @@ -3861,7 +3861,7 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { status: enums::CaptureStatus::foreign_try_from(status)?, connector_capture_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, }) } types::CaptureSyncResponse::Error { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 4d8cc195693..938bf1a8369 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -235,7 +235,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }) @@ -249,7 +249,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }) @@ -332,7 +332,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some(err.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, - connector_refund_data: None, + processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), } @@ -341,7 +341,7 @@ pub async fn trigger_refund_to_gateway( // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { - let (refund_connector_transaction_id, connector_refund_data) = + let (refund_connector_transaction_id, processor_refund_data) = err.connector_transaction_id.map_or((None, None), |txn_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(txn_id); @@ -363,7 +363,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, - connector_refund_data, + processor_refund_data, unified_code: None, unified_message: None, } @@ -378,7 +378,7 @@ pub async fn trigger_refund_to_gateway( )), ) } - let (connector_refund_id, connector_refund_data) = + let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, @@ -387,7 +387,7 @@ pub async fn trigger_refund_to_gateway( refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), - connector_refund_data, + processor_refund_data, } } } @@ -677,7 +677,7 @@ pub async fn sync_refund_with_gateway( refund_error_code: Some(error_message.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, } @@ -691,7 +691,7 @@ pub async fn sync_refund_with_gateway( ("merchant_id", merchant_account.get_id().clone()), ), ); - let (refund_connector_transaction_id, connector_refund_data) = err + let (refund_connector_transaction_id, processor_refund_data) = err .connector_transaction_id .map_or((None, None), |refund_id| { let (refund_id, refund_data) = @@ -707,13 +707,13 @@ pub async fn sync_refund_with_gateway( refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, - connector_refund_data, + processor_refund_data, unified_code: None, unified_message: None, } } Ok(()) => { - let (connector_refund_id, connector_refund_data) = + let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, @@ -722,7 +722,7 @@ pub async fn sync_refund_with_gateway( refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), - connector_refund_data, + processor_refund_data, } } }, @@ -882,7 +882,7 @@ pub async fn validate_and_create_refund( .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = storage::RefundNew { refund_id: refund_id.to_string(), @@ -912,8 +912,8 @@ pub async fn validate_and_create_refund( refund_arn: None, updated_by: Default::default(), organization_id: merchant_account.organization_id.clone(), - connector_refund_data: None, - connector_transaction_data, + processor_transaction_data, + processor_refund_data: None, }; let refund = match db @@ -1584,7 +1584,7 @@ pub fn refund_to_refund_core_workflow_model( connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), - connector_transaction_data: refund.connector_transaction_data.clone(), + processor_transaction_data: refund.processor_transaction_data.clone(), } } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 2c0d9b5b5c5..8b562978804 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1023,7 +1023,7 @@ async fn refunds_incoming_webhook_flow( .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("failed refund status mapping from event type")?, updated_by: merchant_account.storage_scheme.to_string(), - connector_refund_data: None, + processor_refund_data: None, }; db.update_refund( refund.to_owned(), diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs index cbc27f918d4..a2e4a90d66d 100644 --- a/crates/router/src/db/capture.rs +++ b/crates/router/src/db/capture.rs @@ -198,7 +198,9 @@ impl CaptureInterface for MockDb { capture_sequence: capture.capture_sequence, connector_capture_id: capture.connector_capture_id, connector_response_reference_id: capture.connector_response_reference_id, - connector_capture_data: capture.connector_capture_data, + processor_capture_data: capture.processor_capture_data, + // Below fields are deprecated. Please add any new fields above this line. + connector_capture_data: None, }; captures.push(capture.clone()); Ok(capture) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index e07821cd9a8..07bdfa3f77d 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -435,10 +435,13 @@ mod storage { charges: new.charges.clone(), split_refunds: new.split_refunds.clone(), organization_id: new.organization_id.clone(), - connector_refund_data: new.connector_refund_data.clone(), - connector_transaction_data: new.connector_transaction_data.clone(), unified_code: None, unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + // Below fields are deprecated. Please add any new fields above this line. + connector_refund_data: None, + connector_transaction_data: None, }; let field = format!( @@ -620,12 +623,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: Box::new(kv::Updateable::RefundUpdate( + updatable: Box::new(kv::Updateable::RefundUpdate(Box::new( kv::RefundUpdateMems { orig: this, update_data: refund, }, - )), + ))), }, }; @@ -932,10 +935,13 @@ impl RefundInterface for MockDb { charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, - connector_refund_data: new.connector_refund_data, - connector_transaction_data: new.connector_transaction_data, unified_code: None, unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + // Below fields are deprecated. Please add any new fields above this line. + connector_refund_data: None, + connector_transaction_data: None, }; refunds.push(refund.clone()); Ok(refund) diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 1773d7f3a17..c82a921fe17 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -63,6 +63,8 @@ impl PaymentAttemptExt for PaymentAttempt { capture_sequence, connector_capture_id: None, connector_response_reference_id: None, + processor_capture_data: None, + // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }) } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index c5652e6cbfa..e189deb9487 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -277,7 +277,7 @@ pub async fn generate_sample_data( psd2_sca_exemption_type: None, platform_merchant_id: None, }; - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), @@ -359,14 +359,14 @@ pub async fn generate_sample_data( organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, - connector_transaction_data, + processor_transaction_data, connector_mandate_detail: None, card_discovery: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), @@ -401,8 +401,8 @@ pub async fn generate_sample_data( charges: None, split_refunds: None, organization_id: org_id.clone(), - connector_refund_data: None, - connector_transaction_data, + processor_refund_data: None, + processor_transaction_data, }) } else { None diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 0c8b969e166..5b5f50f5aa4 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1490,7 +1490,7 @@ impl DataModelExt for PaymentAttempt { type StorageModel = DieselPaymentAttempt; fn to_storage_model(self) -> Self::StorageModel { - let (connector_transaction_id, connector_transaction_data) = self + let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -1565,12 +1565,14 @@ impl DataModelExt for PaymentAttempt { customer_acceptance: self.customer_acceptance, organization_id: self.organization_id, profile_id: self.profile_id, - connector_transaction_data, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), connector_mandate_detail: self.connector_mandate_detail, + processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + // Below fields are deprecated. Please add any new fields above this line. + connector_transaction_data: None, } } diff --git a/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js b/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js index 06c5c799156..7b783847682 100644 --- a/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js +++ b/cypress-tests/cypress/e2e/configs/Payment/WorldPay.js @@ -695,4 +695,804 @@ export const connectorDetails = { }, }, }, + pm_list: { + PmListResponse: { + pmListDynamicFieldWithoutBilling: { + payment_methods: [ + { + payment_method: "card", + payment_method_types: [ + { + payment_method_type: "credit", + card_networks: [{ eligible_connectors: ["worldpay"] }], + required_fields: { + "payment_method_data.card.card_number": { + required_field: "payment_method_data.card.card_number", + display_name: "card_number", + field_type: "user_card_number", + value: null, + }, + "payment_method_data.card.card_exp_month": { + required_field: "payment_method_data.card.card_exp_month", + display_name: "card_exp_month", + field_type: "user_card_expiry_month", + value: null, + }, + "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.line1": { + required_field: "payment_method_data.billing.address.line1", + display_name: "line1", + field_type: "user_address_line1", + value: null, + }, + "billing.address.country": { + required_field: + "payment_method_data.billing.address.country", + display_name: "country", + field_type: { + user_address_country: { + options: [ + "AF", + "AU", + "AW", + "AZ", + "BS", + "BH", + "BD", + "BB", + "BZ", + "BM", + "BT", + "BO", + "BA", + "BW", + "BR", + "BN", + "BG", + "BI", + "KH", + "CA", + "CV", + "KY", + "CL", + "CO", + "KM", + "CD", + "CR", + "CZ", + "DZ", + "DK", + "DJ", + "ST", + "DO", + "EC", + "EG", + "SV", + "ER", + "ET", + "FK", + "FJ", + "GM", + "GE", + "GH", + "GI", + "GT", + "GN", + "GY", + "HT", + "HN", + "HK", + "HU", + "IS", + "IN", + "ID", + "IR", + "IQ", + "IE", + "IL", + "IT", + "JM", + "JP", + "JO", + "KZ", + "KE", + "KW", + "LA", + "LB", + "LS", + "LR", + "LY", + "LT", + "MO", + "MK", + "MG", + "MW", + "MY", + "MV", + "MR", + "MU", + "MX", + "MD", + "MN", + "MA", + "MZ", + "MM", + "NA", + "NZ", + "NI", + "NG", + "KP", + "NO", + "AR", + "PK", + "PG", + "PY", + "PE", + "UY", + "PH", + "PL", + "GB", + "QA", + "OM", + "RO", + "RU", + "RW", + "WS", + "SG", + "ST", + "ZA", + "KR", + "LK", + "SH", + "SD", + "SR", + "SZ", + "SE", + "CH", + "SY", + "TW", + "TJ", + "TZ", + "TH", + "TT", + "TN", + "TR", + "UG", + "UA", + "US", + "UZ", + "VU", + "VE", + "VN", + "ZM", + "ZW", + ], + }, + }, + value: null, + }, + "billing.address.city": { + required_field: "payment_method_data.billing.address.city", + display_name: "city", + field_type: "user_address_city", + value: null, + }, + "billing.address.zip": { + required_field: "payment_method_data.billing.address.zip", + display_name: "zip", + field_type: "user_address_pincode", + value: null, + }, + }, + }, + ], + }, + ], + }, + pmListDynamicFieldWithBilling: { + payment_methods: [ + { + payment_method: "card", + payment_method_types: [ + { + payment_method_type: "credit", + card_networks: [{ eligible_connectors: ["worldpay"] }], + required_fields: { + "payment_method_data.card.card_number": { + required_field: "payment_method_data.card.card_number", + display_name: "card_number", + field_type: "user_card_number", + value: null, + }, + "payment_method_data.card.card_exp_month": { + required_field: "payment_method_data.card.card_exp_month", + display_name: "card_exp_month", + field_type: "user_card_expiry_month", + value: null, + }, + "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.line1": { + required_field: "payment_method_data.billing.address.line1", + display_name: "line1", + field_type: "user_address_line1", + value: "1467", + }, + "billing.address.country": { + required_field: + "payment_method_data.billing.address.country", + display_name: "country", + field_type: { + user_address_country: { + options: [ + "AF", + "AU", + "AW", + "AZ", + "BS", + "BH", + "BD", + "BB", + "BZ", + "BM", + "BT", + "BO", + "BA", + "BW", + "BR", + "BN", + "BG", + "BI", + "KH", + "CA", + "CV", + "KY", + "CL", + "CO", + "KM", + "CD", + "CR", + "CZ", + "DZ", + "DK", + "DJ", + "ST", + "DO", + "EC", + "EG", + "SV", + "ER", + "ET", + "FK", + "FJ", + "GM", + "GE", + "GH", + "GI", + "GT", + "GN", + "GY", + "HT", + "HN", + "HK", + "HU", + "IS", + "IN", + "ID", + "IR", + "IQ", + "IE", + "IL", + "IT", + "JM", + "JP", + "JO", + "KZ", + "KE", + "KW", + "LA", + "LB", + "LS", + "LR", + "LY", + "LT", + "MO", + "MK", + "MG", + "MW", + "MY", + "MV", + "MR", + "MU", + "MX", + "MD", + "MN", + "MA", + "MZ", + "MM", + "NA", + "NZ", + "NI", + "NG", + "KP", + "NO", + "AR", + "PK", + "PG", + "PY", + "PE", + "UY", + "PH", + "PL", + "GB", + "QA", + "OM", + "RO", + "RU", + "RW", + "WS", + "SG", + "ST", + "ZA", + "KR", + "LK", + "SH", + "SD", + "SR", + "SZ", + "SE", + "CH", + "SY", + "TW", + "TJ", + "TZ", + "TH", + "TT", + "TN", + "TR", + "UG", + "UA", + "US", + "UZ", + "VU", + "VE", + "VN", + "ZM", + "ZW", + ], + }, + }, + value: "PL", + }, + "billing.address.city": { + required_field: "payment_method_data.billing.address.city", + display_name: "city", + field_type: "user_address_city", + value: "San Fransico", + }, + "billing.address.zip": { + required_field: "payment_method_data.billing.address.zip", + display_name: "zip", + field_type: "user_address_pincode", + value: "94122", + }, + }, + }, + ], + }, + ], + }, + pmListDynamicFieldWithNames: { + payment_methods: [ + { + payment_method: "card", + payment_method_types: [ + { + payment_method_type: "credit", + card_networks: [ + { + eligible_connectors: ["worldpay"], + }, + ], + required_fields: { + "billing.address.country": { + required_field: + "payment_method_data.billing.address.country", + display_name: "country", + field_type: { + user_address_country: { + options: [ + "AF", + "AU", + "AW", + "AZ", + "BS", + "BH", + "BD", + "BB", + "BZ", + "BM", + "BT", + "BO", + "BA", + "BW", + "BR", + "BN", + "BG", + "BI", + "KH", + "CA", + "CV", + "KY", + "CL", + "CO", + "KM", + "CD", + "CR", + "CZ", + "DZ", + "DK", + "DJ", + "ST", + "DO", + "EC", + "EG", + "SV", + "ER", + "ET", + "FK", + "FJ", + "GM", + "GE", + "GH", + "GI", + "GT", + "GN", + "GY", + "HT", + "HN", + "HK", + "HU", + "IS", + "IN", + "ID", + "IR", + "IQ", + "IE", + "IL", + "IT", + "JM", + "JP", + "JO", + "KZ", + "KE", + "KW", + "LA", + "LB", + "LS", + "LR", + "LY", + "LT", + "MO", + "MK", + "MG", + "MW", + "MY", + "MV", + "MR", + "MU", + "MX", + "MD", + "MN", + "MA", + "MZ", + "MM", + "NA", + "NZ", + "NI", + "NG", + "KP", + "NO", + "AR", + "PK", + "PG", + "PY", + "PE", + "UY", + "PH", + "PL", + "GB", + "QA", + "OM", + "RO", + "RU", + "RW", + "WS", + "SG", + "ST", + "ZA", + "KR", + "LK", + "SH", + "SD", + "SR", + "SZ", + "SE", + "CH", + "SY", + "TW", + "TJ", + "TZ", + "TH", + "TT", + "TN", + "TR", + "UG", + "UA", + "US", + "UZ", + "VU", + "VE", + "VN", + "ZM", + "ZW", + ], + }, + }, + value: null, + }, + "billing.address.zip": { + required_field: "payment_method_data.billing.address.zip", + display_name: "zip", + field_type: "user_address_pincode", + value: null, + }, + "billing.address.city": { + required_field: "payment_method_data.billing.address.city", + display_name: "city", + field_type: "user_address_city", + value: null, + }, + "billing.address.line1": { + required_field: "payment_method_data.billing.address.line1", + display_name: "line1", + field_type: "user_address_line1", + value: null, + }, + "payment_method_data.card.card_exp_year": { + required_field: "payment_method_data.card.card_exp_year", + display_name: "card_exp_year", + field_type: "user_card_expiry_year", + value: null, + }, + "payment_method_data.card.card_number": { + required_field: "payment_method_data.card.card_number", + display_name: "card_number", + field_type: "user_card_number", + value: null, + }, + "payment_method_data.card.card_exp_month": { + required_field: "payment_method_data.card.card_exp_month", + display_name: "card_exp_month", + field_type: "user_card_expiry_month", + value: null, + }, + }, + }, + ], + }, + ], + }, + pmListDynamicFieldWithEmail: { + payment_methods: [ + { + payment_method: "card", + payment_method_types: [ + { + payment_method_type: "credit", + card_networks: [ + { + eligible_connectors: ["worldpay"], + }, + ], + required_fields: { + "payment_method_data.card.card_exp_year": { + required_field: "payment_method_data.card.card_exp_year", + display_name: "card_exp_year", + field_type: "user_card_expiry_year", + value: null, + }, + "payment_method_data.card.card_number": { + required_field: "payment_method_data.card.card_number", + display_name: "card_number", + field_type: "user_card_number", + value: null, + }, + "payment_method_data.card.card_exp_month": { + required_field: "payment_method_data.card.card_exp_month", + display_name: "card_exp_month", + field_type: "user_card_expiry_month", + value: null, + }, + "billing.address.zip": { + required_field: "payment_method_data.billing.address.zip", + display_name: "zip", + field_type: "user_address_pincode", + value: null, + }, + "billing.address.city": { + required_field: "payment_method_data.billing.address.city", + display_name: "city", + field_type: "user_address_city", + value: null, + }, + "billing.address.line1": { + required_field: "payment_method_data.billing.address.line1", + display_name: "line1", + field_type: "user_address_line1", + value: null, + }, + "billing.address.country": { + required_field: + "payment_method_data.billing.address.country", + display_name: "country", + field_type: { + user_address_country: { + options: [ + "AF", + "AU", + "AW", + "AZ", + "BS", + "BH", + "BD", + "BB", + "BZ", + "BM", + "BT", + "BO", + "BA", + "BW", + "BR", + "BN", + "BG", + "BI", + "KH", + "CA", + "CV", + "KY", + "CL", + "CO", + "KM", + "CD", + "CR", + "CZ", + "DZ", + "DK", + "DJ", + "ST", + "DO", + "EC", + "EG", + "SV", + "ER", + "ET", + "FK", + "FJ", + "GM", + "GE", + "GH", + "GI", + "GT", + "GN", + "GY", + "HT", + "HN", + "HK", + "HU", + "IS", + "IN", + "ID", + "IR", + "IQ", + "IE", + "IL", + "IT", + "JM", + "JP", + "JO", + "KZ", + "KE", + "KW", + "LA", + "LB", + "LS", + "LR", + "LY", + "LT", + "MO", + "MK", + "MG", + "MW", + "MY", + "MV", + "MR", + "MU", + "MX", + "MD", + "MN", + "MA", + "MZ", + "MM", + "NA", + "NZ", + "NI", + "NG", + "KP", + "NO", + "AR", + "PK", + "PG", + "PY", + "PE", + "UY", + "PH", + "PL", + "GB", + "QA", + "OM", + "RO", + "RU", + "RW", + "WS", + "SG", + "ST", + "ZA", + "KR", + "LK", + "SH", + "SD", + "SR", + "SZ", + "SE", + "CH", + "SY", + "TW", + "TJ", + "TZ", + "TH", + "TT", + "TN", + "TR", + "UG", + "UA", + "US", + "UZ", + "VU", + "VE", + "VN", + "ZM", + "ZW", + ], + }, + }, + value: null, + }, + }, + }, + ], + }, + ], + }, + }, + }, }; diff --git a/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql b/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql new file mode 100644 index 00000000000..bbba634e6e2 --- /dev/null +++ b/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql @@ -0,0 +1,8 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS processor_transaction_data; + +ALTER TABLE refund DROP COLUMN IF EXISTS processor_refund_data; + +ALTER TABLE refund DROP COLUMN IF EXISTS processor_transaction_data; + +ALTER TABLE captures DROP COLUMN IF EXISTS processor_capture_data; \ No newline at end of file diff --git a/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql b/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql new file mode 100644 index 00000000000..81e9cdcd074 --- /dev/null +++ b/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql @@ -0,0 +1,11 @@ +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS processor_transaction_data TEXT; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS processor_refund_data TEXT; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS processor_transaction_data TEXT; + +ALTER TABLE captures +ADD COLUMN IF NOT EXISTS processor_capture_data TEXT; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql index 3926a02afa6..03059985875 100644 --- a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql +++ b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql @@ -51,7 +51,7 @@ ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA, ADD COLUMN redirection_data JSONB, - ADD COLUMN connector_payment_data VARCHAR(512), + ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB diff --git a/v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql similarity index 98% rename from v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql rename to v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql index f67b9b2e7ac..8d0fedce089 100644 --- a/v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql @@ -76,7 +76,7 @@ ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64) NOT NULL, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(64), - ADD COLUMN connector_transaction_data VARCHAR(512), + ADD COLUMN connector_transaction_data TEXT, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), diff --git a/v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql similarity index 92% rename from v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql rename to v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index e19f8631f62..caac00abd0f 100644 --- a/v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -75,6 +75,7 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN payment_method, DROP COLUMN connector_transaction_id, DROP COLUMN connector_transaction_data, + DROP COLUMN processor_transaction_data, DROP COLUMN capture_method, DROP COLUMN capture_on, DROP COLUMN mandate_id, @@ -89,3 +90,10 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN payment_method_billing_address_id, DROP COLUMN connector_mandate_detail, DROP COLUMN charge_id; + +-- Run below queries only when V1 is deprecated +ALTER TABLE refund DROP COLUMN connector_refund_data, + DROP COLUMN connector_transaction_data; + +-- Run below queries only when V1 is deprecated +ALTER TABLE captures DROP COLUMN connector_capture_data;
refactor
add a new column for storing large connector transaction IDs (#7017)
93976db30a91b3e67d854681fb4b9db8eea7e295
2024-07-26 12:39:34
Narayan Bhat
refactor(merchant_account_v2): recreate id for `merchant_account` v2 (#5439)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 4f1143efaa8..2819dbbb258 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -440,7 +440,7 @@ pub struct MerchantAccountResponse { pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")] - pub id: String, + pub id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = String,example = "NewAge Retailer")] diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 23bc642c2db..3aa4088f3b0 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -1,4 +1,4 @@ -use common_utils::{encryption::Encryption, id_type, pii}; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; @@ -10,6 +10,9 @@ use crate::schema::merchant_account; #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] use crate::schema_v2::merchant_account; +/// Note: The order of fields in the struct is important. +/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile +/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "merchant_account_v2") @@ -26,7 +29,7 @@ use crate::schema_v2::merchant_account; )] #[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { - pub merchant_id: id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, @@ -35,7 +38,7 @@ pub struct MerchantAccount { pub merchant_details: Option<Encryption>, pub webhook_details: Option<serde_json::Value>, pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<id_type::MerchantId>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, @@ -47,7 +50,7 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, - pub organization_id: id_type::OrganizationId, + pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, @@ -55,6 +58,81 @@ pub struct MerchantAccount { pub pm_collect_link_config: Option<serde_json::Value>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +pub struct MerchantAccountSetter { + pub merchant_id: common_utils::id_type::MerchantId, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub merchant_name: Option<Encryption>, + pub merchant_details: Option<Encryption>, + pub webhook_details: Option<serde_json::Value>, + pub sub_merchants_enabled: Option<bool>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, + pub publishable_key: Option<String>, + pub storage_scheme: storage_enums::MerchantStorageScheme, + pub locker_id: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub primary_business_details: serde_json::Value, + pub intent_fulfillment_time: Option<i64>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub organization_id: common_utils::id_type::OrganizationId, + pub is_recon_enabled: bool, + pub default_profile: Option<String>, + pub recon_status: storage_enums::ReconStatus, + pub payment_link_config: Option<serde_json::Value>, + pub pm_collect_link_config: Option<serde_json::Value>, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl From<MerchantAccountSetter> for MerchantAccount { + fn from(item: MerchantAccountSetter) -> Self { + Self { + merchant_id: item.merchant_id, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + merchant_name: item.merchant_name, + merchant_details: item.merchant_details, + webhook_details: item.webhook_details, + sub_merchants_enabled: item.sub_merchants_enabled, + parent_merchant_id: item.parent_merchant_id, + publishable_key: item.publishable_key, + storage_scheme: item.storage_scheme, + locker_id: item.locker_id, + metadata: item.metadata, + routing_algorithm: item.routing_algorithm, + primary_business_details: item.primary_business_details, + intent_fulfillment_time: item.intent_fulfillment_time, + created_at: item.created_at, + modified_at: item.modified_at, + frm_routing_algorithm: item.frm_routing_algorithm, + payout_routing_algorithm: item.payout_routing_algorithm, + organization_id: item.organization_id, + is_recon_enabled: item.is_recon_enabled, + default_profile: item.default_profile, + recon_status: item.recon_status, + payment_link_config: item.payment_link_config, + pm_collect_link_config: item.pm_collect_link_config, + } + } +} + +/// Note: The order of fields in the struct is important. +/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile +/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] #[derive( Clone, @@ -66,9 +144,8 @@ pub struct MerchantAccount { router_derive::DebugAsDisplay, Selectable, )] -#[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { - pub merchant_id: id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, @@ -89,7 +166,74 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, - pub organization_id: id_type::OrganizationId, + pub organization_id: common_utils::id_type::OrganizationId, + pub is_recon_enabled: bool, + pub default_profile: Option<String>, + pub recon_status: storage_enums::ReconStatus, + pub payment_link_config: Option<serde_json::Value>, + pub pm_collect_link_config: Option<serde_json::Value>, + pub id: common_utils::id_type::MerchantId, +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl From<MerchantAccountSetter> for MerchantAccount { + fn from(item: MerchantAccountSetter) -> Self { + Self { + id: item.id, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + merchant_name: item.merchant_name, + merchant_details: item.merchant_details, + webhook_details: item.webhook_details, + sub_merchants_enabled: item.sub_merchants_enabled, + parent_merchant_id: item.parent_merchant_id, + publishable_key: item.publishable_key, + storage_scheme: item.storage_scheme, + locker_id: item.locker_id, + metadata: item.metadata, + routing_algorithm: item.routing_algorithm, + primary_business_details: item.primary_business_details, + intent_fulfillment_time: item.intent_fulfillment_time, + created_at: item.created_at, + modified_at: item.modified_at, + frm_routing_algorithm: item.frm_routing_algorithm, + payout_routing_algorithm: item.payout_routing_algorithm, + organization_id: item.organization_id, + is_recon_enabled: item.is_recon_enabled, + default_profile: item.default_profile, + recon_status: item.recon_status, + payment_link_config: item.payment_link_config, + pm_collect_link_config: item.pm_collect_link_config, + } + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +pub struct MerchantAccountSetter { + pub id: common_utils::id_type::MerchantId, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub merchant_name: Option<Encryption>, + pub merchant_details: Option<Encryption>, + pub webhook_details: Option<serde_json::Value>, + pub sub_merchants_enabled: Option<bool>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, + pub publishable_key: Option<String>, + pub storage_scheme: storage_enums::MerchantStorageScheme, + pub locker_id: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub primary_business_details: serde_json::Value, + pub intent_fulfillment_time: Option<i64>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, @@ -98,21 +242,35 @@ pub struct MerchantAccount { } impl MerchantAccount { - pub fn get_id(&self) -> &id_type::MerchantId { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] + /// Get the unique identifier of MerchantAccount + pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } + + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + pub fn get_id(&self) -> &common_utils::id_type::MerchantId { + &self.id + } } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { - pub merchant_id: id_type::MerchantId, + pub merchant_id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<serde_json::Value>, pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<id_type::MerchantId>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, @@ -126,7 +284,7 @@ pub struct MerchantAccountNew { pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, - pub organization_id: id_type::OrganizationId, + pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, @@ -134,6 +292,38 @@ pub struct MerchantAccountNew { pub pm_collect_link_config: Option<serde_json::Value>, } +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = merchant_account)] +pub struct MerchantAccountNew { + pub merchant_name: Option<Encryption>, + pub merchant_details: Option<Encryption>, + pub return_url: Option<String>, + pub webhook_details: Option<serde_json::Value>, + pub sub_merchants_enabled: Option<bool>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, + pub enable_payment_response_hash: Option<bool>, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: Option<bool>, + pub publishable_key: Option<String>, + pub locker_id: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub primary_business_details: serde_json::Value, + pub intent_fulfillment_time: Option<i64>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub organization_id: common_utils::id_type::OrganizationId, + pub is_recon_enabled: bool, + pub default_profile: Option<String>, + pub recon_status: storage_enums::ReconStatus, + pub payment_link_config: Option<serde_json::Value>, + pub pm_collect_link_config: Option<serde_json::Value>, + pub id: common_utils::id_type::MerchantId, +} + #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { @@ -142,7 +332,7 @@ pub struct MerchantAccountUpdateInternal { pub return_url: Option<String>, pub webhook_details: Option<serde_json::Value>, pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<id_type::MerchantId>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, @@ -156,7 +346,7 @@ pub struct MerchantAccountUpdateInternal { pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, - pub organization_id: Option<id_type::OrganizationId>, + pub organization_id: Option<common_utils::id_type::OrganizationId>, pub is_recon_enabled: bool, pub default_profile: Option<Option<String>>, pub recon_status: Option<storage_enums::ReconStatus>, diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index 578a1002199..564a37d79e1 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -5,9 +5,9 @@ use super::generics; any(feature = "v1", feature = "v2"), not(feature = "merchant_account_v2") ))] -use crate::schema::merchant_account::dsl; +use crate::schema::merchant_account::dsl::{self, merchant_id as dsl_identifier}; #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] -use crate::schema_v2::merchant_account::dsl; +use crate::schema_v2::merchant_account::dsl::{self, id as dsl_identifier}; use crate::{ errors, merchant_account::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal}, @@ -28,7 +28,7 @@ impl MerchantAccount { ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, - self.merchant_id.clone(), + self.get_id().to_owned(), merchant_account, ) .await @@ -43,7 +43,7 @@ impl MerchantAccount { pub async fn update_with_specific_fields( conn: &PgPooledConn, - merchant_id: &common_utils::id_type::MerchantId, + identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< @@ -53,7 +53,7 @@ impl MerchantAccount { _, >( conn, - dsl::merchant_id.eq(merchant_id.to_owned()), + dsl_identifier.eq(identifier.to_owned()), merchant_account, ) .await @@ -61,22 +61,22 @@ impl MerchantAccount { pub async fn delete_by_merchant_id( conn: &PgPooledConn, - merchant_id: &common_utils::id_type::MerchantId, + identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, - dsl::merchant_id.eq(merchant_id.to_owned()), + dsl_identifier.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, - merchant_id: &common_utils::id_type::MerchantId, + identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, - dsl::merchant_id.eq(merchant_id.to_owned()), + dsl_identifier.eq(identifier.to_owned()), ) .await } @@ -120,13 +120,7 @@ impl MerchantAccount { _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, - >( - conn, - dsl::merchant_id.eq_any(merchant_ids), - None, - None, - None, - ) + >(conn, dsl_identifier.eq_any(merchant_ids), None, None, None) .await } @@ -136,7 +130,7 @@ impl MerchantAccount { ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::merchant_id.ne_all(vec![""]), + dsl_identifier.ne_all(vec![""]), merchant_account, ) .await diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 28937b48db4..ca6a7208252 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -633,9 +633,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - merchant_account (merchant_id) { - #[max_length = 64] - merchant_id -> Varchar, + merchant_account (id) { #[max_length = 255] return_url -> Nullable<Varchar>, enable_payment_response_hash -> Bool, @@ -669,6 +667,8 @@ diesel::table! { recon_status -> ReconStatus, payment_link_config -> Nullable<Jsonb>, pm_collect_link_config -> Nullable<Jsonb>, + #[max_length = 64] + id -> Varchar, } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 6d311ea2d4d..ce11cd566c6 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -125,10 +125,78 @@ impl From<MerchantAccountSetter> for MerchantAccount { } } +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone)] +/// Set the private fields of merchant account +pub struct MerchantAccountSetter { + pub id: common_utils::id_type::MerchantId, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub merchant_name: OptionalEncryptableName, + pub merchant_details: OptionalEncryptableValue, + pub webhook_details: Option<serde_json::Value>, + pub sub_merchants_enabled: Option<bool>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, + pub publishable_key: String, + pub storage_scheme: MerchantStorageScheme, + pub locker_id: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub primary_business_details: serde_json::Value, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub intent_fulfillment_time: Option<i64>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub organization_id: common_utils::id_type::OrganizationId, + pub is_recon_enabled: bool, + pub default_profile: Option<String>, + pub recon_status: diesel_models::enums::ReconStatus, + pub payment_link_config: Option<serde_json::Value>, + pub pm_collect_link_config: Option<serde_json::Value>, +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl From<MerchantAccountSetter> for MerchantAccount { + fn from(item: MerchantAccountSetter) -> Self { + Self { + id: item.id, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + merchant_name: item.merchant_name, + merchant_details: item.merchant_details, + webhook_details: item.webhook_details, + sub_merchants_enabled: item.sub_merchants_enabled, + parent_merchant_id: item.parent_merchant_id, + publishable_key: item.publishable_key, + storage_scheme: item.storage_scheme, + locker_id: item.locker_id, + metadata: item.metadata, + routing_algorithm: item.routing_algorithm, + primary_business_details: item.primary_business_details, + frm_routing_algorithm: item.frm_routing_algorithm, + created_at: item.created_at, + modified_at: item.modified_at, + intent_fulfillment_time: item.intent_fulfillment_time, + payout_routing_algorithm: item.payout_routing_algorithm, + organization_id: item.organization_id, + is_recon_enabled: item.is_recon_enabled, + default_profile: item.default_profile, + recon_status: item.recon_status, + payment_link_config: item.payment_link_config, + pm_collect_link_config: item.pm_collect_link_config, + } + } +} + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { - merchant_id: common_utils::id_type::MerchantId, + id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, @@ -137,7 +205,7 @@ pub struct MerchantAccount { pub merchant_details: OptionalEncryptableValue, pub webhook_details: Option<serde_json::Value>, pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<String>, + pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub locker_id: Option<String>, @@ -158,10 +226,20 @@ pub struct MerchantAccount { } impl MerchantAccount { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } + + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + /// Get the unique identifier of MerchantAccount + pub fn get_id(&self) -> &common_utils::id_type::MerchantId { + &self.id + } } #[allow(clippy::large_enum_variant)] @@ -278,8 +356,10 @@ impl super::behaviour::Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { - Ok(diesel_models::merchant_account::MerchantAccount { - merchant_id: self.merchant_id, + let id = self.get_id().to_owned(); + + let setter = diesel_models::merchant_account::MerchantAccountSetter { + id, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, @@ -306,7 +386,9 @@ impl super::behaviour::Conversion for MerchantAccount { recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, - }) + }; + + Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( @@ -318,6 +400,7 @@ impl super::behaviour::Conversion for MerchantAccount { where Self: Sized, { + let id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { @@ -326,7 +409,7 @@ impl super::behaviour::Conversion for MerchantAccount { async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - merchant_id: item.merchant_id, + id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, @@ -374,7 +457,7 @@ impl super::behaviour::Conversion for MerchantAccount { async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::merchant_account::MerchantAccountNew { - merchant_id: self.merchant_id, + id: self.id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), return_url: self.return_url, @@ -413,7 +496,7 @@ impl super::behaviour::Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { - Ok(diesel_models::merchant_account::MerchantAccount { + let setter = diesel_models::merchant_account::MerchantAccountSetter { merchant_id: self.merchant_id, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, @@ -441,7 +524,9 @@ impl super::behaviour::Conversion for MerchantAccount { recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, - }) + }; + + Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( @@ -453,14 +538,16 @@ impl super::behaviour::Conversion for MerchantAccount { where Self: Sized, { + let merchant_id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; + async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - merchant_id: item.merchant_id, + merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 9203a33239e..15c5aded500 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -554,7 +554,7 @@ impl behaviour::Conversion for PaymentIntent { { async { let inner_decrypt = - |inner| decrypt_optional(state, inner, key_manager_identifier, key.peek()); + |inner| decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek()); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 51fffea3b53..70037725569 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -412,7 +412,10 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { #[cfg(feature = "olap")] enum CreateOrValidateOrganization { /// Creates a new organization - #[cfg(any(feature = "v1", feature = "v2"))] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] Create, /// Validates if this organization exists in the records Validate { @@ -451,7 +454,10 @@ impl CreateOrValidateOrganization { db: &dyn StorageInterface, ) -> RouterResult<diesel_models::organization::Organization> { match self { - #[cfg(any(feature = "v1", feature = "v2"))] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] Self::Create => { let new_organization = api_models::organization::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); @@ -637,17 +643,14 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .await?; let key = key_store.key.into_inner(); - let merchant_id = self - .get_merchant_reference_id() - .get_string_repr() - .to_owned(); + let id = self.get_merchant_reference_id().to_owned(); let key_manager_state = state.into(); - let identifier = km_types::Identifier::Merchant(merchant_id.clone()); + let identifier = km_types::Identifier::Merchant(id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - domain::MerchantAccount { - merchant_id, + domain::MerchantAccount::from(domain::MerchantAccountSetter { + id, merchant_name: Some( domain_types::encrypt( &key_manager_state, @@ -695,7 +698,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config: None, - }, + }), ) } .await diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 4c96f4fbe8f..a2081abddca 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -206,7 +206,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let _default_customer_billing_address = self.get_default_customer_billing_address(); let _default_customer_shipping_address = self.get_default_customer_shipping_address(); - let merchant_id = merchant_account.merchant_id.clone(); + let merchant_id = merchant_account.get_id().clone(); let key = key_store.key.get_inner().peek(); let encrypted_data = types::batch_encrypt( @@ -230,14 +230,13 @@ impl CustomerCreateBridge for customers::CustomerRequest { customer_id: merchant_reference_id .to_owned() .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // doing this to make it compile, will remove once we start moving to domain models - merchant_id: merchant_id.to_string(), + merchant_id, name: encryptable_customer.name, email: encryptable_customer.email, phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), - id: None, connector_customer: None, address_id: None, created_at: common_utils::date_time::now(), diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 1907b9bdea8..aee54b3e1b5 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -483,7 +483,7 @@ impl MerchantAccountInterface for MockDb { let accounts = self.merchant_accounts.lock().await; let account: Option<domain::MerchantAccount> = accounts .iter() - .find(|account| account.merchant_id == *merchant_id) + .find(|account| account.get_id() == merchant_id) .cloned() .async_map(|a| async { a.convert( @@ -608,7 +608,7 @@ async fn publish_and_redact_all_merchant_account_cache( ) -> CustomResult<(), errors::StorageError> { let merchant_ids = merchant_accounts .iter() - .map(|m| m.merchant_id.get_string_repr().to_string()); + .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 8d456bb8fd8..6dfb74c3781 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -20,8 +20,12 @@ use tokio::sync::oneshot; use self::settings::Tenant; #[cfg(feature = "olap")] use super::blocklist; +#[cfg(any(feature = "olap", feature = "oltp"))] +use super::currency; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; +#[cfg(all(any(feature = "olap", feature = "oltp"), not(feature = "customer_v2")))] +use super::payment_methods::*; #[cfg(feature = "payouts")] use super::payout_link::*; #[cfg(feature = "payouts")] @@ -46,8 +50,6 @@ 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::*, webhooks::*}; #[cfg(feature = "olap")] @@ -58,8 +60,6 @@ use crate::analytics::AnalyticsProvider; use crate::routes::fraud_check as frm_routes; #[cfg(all(feature = "recon", feature = "olap"))] use crate::routes::recon as recon_routes; -#[cfg(all(feature = "olap", not(feature = "v2")))] -use crate::routes::verify_connector::payment_connector_verify; pub use crate::{ configs::settings, core::routing, @@ -1116,7 +1116,7 @@ impl MerchantConnectorAccount { route = route .service( web::resource("/connectors/verify") - .route(web::post().to(payment_connector_verify)), + .route(web::post().to(super::verify_connector::payment_connector_verify)), ) .service( web::resource("/{merchant_id}/connectors") diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 04333087927..9669b8326d9 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -91,13 +91,15 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; + let id = item.get_id().to_owned(); + let merchant_name = item .merchant_name .get_required_value("merchant_name")? .into_inner(); Ok(Self { - id: item.merchant_id, + id, merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index c86f9240c4b..6798cdc3ea3 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -22,17 +22,14 @@ use api_models::{ }; use base64::Engine; use common_utils::types::keymanager::KeyManagerState; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] +use common_utils::types::keymanager::{Identifier, ToEncryptable}; pub use common_utils::{ crypto, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, validation::validate_email, }; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -use common_utils::{ - id_type, - types::keymanager::{Identifier, ToEncryptable}, -}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] @@ -677,15 +674,15 @@ pub trait CustomerAddress { address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, - merchant_id: id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, - merchant_id: &id_type::MerchantId, - customer_id: &id_type::CustomerId, + merchant_id: &common_utils::id_type::MerchantId, + customer_id: &common_utils::id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; @@ -700,7 +697,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest { address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, - merchant_id: id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = batch_encrypt( &state.into(), @@ -736,8 +733,8 @@ impl CustomerAddress for api_models::customers::CustomerRequest { &self, state: &SessionState, address_details: payments::AddressDetails, - merchant_id: &id_type::MerchantId, - customer_id: &id_type::CustomerId, + merchant_id: &common_utils::id_type::MerchantId, + customer_id: &common_utils::id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { @@ -784,7 +781,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest { pub fn add_apple_pay_flow_metrics( apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, - merchant_id: id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, ) { if let Some(flow) = apple_pay_flow { match flow { @@ -818,7 +815,7 @@ pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, - merchant_id: id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { diff --git a/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/down.sql b/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/down.sql new file mode 100644 index 00000000000..82fc50e6f42 --- /dev/null +++ b/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account DROP id; diff --git a/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/up.sql b/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/up.sql new file mode 100644 index 00000000000..a84fe8a79c6 --- /dev/null +++ b/v2_migrations/2024-07-25-064644_add_id_in_merchant_account/up.sql @@ -0,0 +1,5 @@ +-- Your SQL goes here +-- Adding a new column called `id` which will be the new primary key for v2 +-- Note that even though this will be the new primary key, the v1 application would still fill in null values +ALTER TABLE merchant_account +ADD COLUMN id VARCHAR(64); diff --git a/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/down.sql b/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/down.sql new file mode 100644 index 00000000000..e3870f59827 --- /dev/null +++ b/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/down.sql @@ -0,0 +1,16 @@ +-- This file should undo anything in `up.sql` +-- The new primary key for v2 merchant account will be `id` +ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey; + +-- In order to run this query, the merchant_id column should be unique and not null +-- We need to backfill the id, a simple strategy will be to copy the values of id to merchant_id +-- Query to update the merchant_id column with values of id +UPDATE merchant_account +SET merchant_id = id; + +-- Note: This command might not run successfully for the existing table +-- This is because there will be some rows ( which are created via v2 application ) which will have id as empty +-- A backfill might be required to run this query +-- However if this is being run on a fresh database, this should succeed +ALTER TABLE merchant_account +ADD PRIMARY KEY (merchant_id); diff --git a/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/up.sql b/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/up.sql new file mode 100644 index 00000000000..ef983789077 --- /dev/null +++ b/v2_migrations/2024-07-25-065100_change_primary_key_from_merchant_id_to_id/up.sql @@ -0,0 +1,17 @@ +-- Your SQL goes here +-- The new primary key for v2 merchant account will be `id` +ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey; + +-- In order to make id as primary key, it should be unique and not null +-- We need to backfill the id, a simple strategy will be to copy the values of merchant_id to id +-- Query to update the id column with values of merchant_id +-- Note: This query will lock the table, so it should be run when there is no traffic +UPDATE merchant_account +SET id = merchant_id; + +-- Note: This command might not run successfully for the existing table +-- This is because there will be some rows ( which are created via v1 application ) which will have id as empty +-- A backfill might be required to run this query +-- However if this is being run on a fresh database, this should succeed +ALTER TABLE merchant_account +ADD PRIMARY KEY (id); diff --git a/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/down.sql b/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/down.sql new file mode 100644 index 00000000000..d4f61709add --- /dev/null +++ b/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account +ADD COLUMN merchant_id VARCHAR(64); diff --git a/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/up.sql b/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/up.sql new file mode 100644 index 00000000000..9bdf043ebda --- /dev/null +++ b/v2_migrations/2024-07-25-065542_drop_merchant_id_from_merchant_account/up.sql @@ -0,0 +1,4 @@ +-- Your SQL goes here +-- Note: This query should not be run on higher environments as this leads to data loss +-- The application will work fine even without these queries not being run +ALTER TABLE merchant_account DROP merchant_id;
refactor
recreate id for `merchant_account` v2 (#5439)
61d31dc44494a7a384d4034655ddfef95a9be24f
2024-06-28 19:21:49
Apoorv Dixit
ci(postman): log request id for user tests (#5159)
false
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js index 16fca64a141..a9297538452 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 4xx pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () { pm.response.to.have.status(401); diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js index a8b3658e5ff..9105ce122cb 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () { pm.response.to.be.success; diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js index e0149290da6..6cb6b69ba6c 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status code is 4xx Bad Request pm.test("[POST]::/user/v2/signin - Status code is 401", function () { pm.response.to.have.status(401); diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js index 174cbd8e5e2..4724ff5981f 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () { pm.response.to.be.success; diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js index 6dbed06b0f6..0c6426d4cfe 100644 --- a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js @@ -1,3 +1,5 @@ +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); + // Validate status 2xx pm.test("[POST]::/user/connect_account - Status code is 2xx", function () { pm.response.to.be.success; @@ -21,3 +23,4 @@ pm.test("[POST]::/user/connect_account - Response contains is_email_sent", funct pm.expect(jsonData).to.have.property("is_email_sent"); pm.expect(jsonData.is_email_sent).to.be.true; }); + diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json index 943d37d22d3..d6067fd668c 100644 --- a/postman/collection-json/users.postman_collection.json +++ b/postman/collection-json/users.postman_collection.json @@ -1,556 +1,567 @@ { - "event": [ - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "test", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "item": [ - { - "name": "Health check", - "item": [ - { - "name": "New Request", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Flow Testcases", - "item": [ - { - "name": "Sign Up", - "item": [ - { - "name": "Connect Account", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/connect_account - 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]::/user/connect_account - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"is_email_sent\");", - " pm.expect(jsonData.is_email_sent).to.be.true;", - "});", - "" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "", - "var baseEmail = pm.environment.get('user_base_email_for_signup');", - "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", - "", - "// Generate a unique email address", - "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", - "// Set the unique email address as an environment variable", - "pm.environment.set('unique_email', uniqueEmail);", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{unique_email}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/connect_account", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "connect_account" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Sign In", - "item": [ - { - "name": "Signin", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"token\");", - " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", - "});" - ], - "type": "text/javascript" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ] - } - }, - "response": [] - }, - { - "name": "Signin Wrong", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status code is 4xx Bad Request", - "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", - " pm.response.to.have.status(401);", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ] - } - }, - "response": [] - }, - { - "name": "Signin Token Only", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Validate specific JSON response content", - "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", - " var jsonData = pm.response.json();", - " pm.expect(jsonData).to.have.property(\"token\");", - " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin?token_only=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ], - "query": [ - { - "key": "token_only", - "value": "true" - } - ] - } - }, - "response": [] - }, - { - "name": "Signin Token Only Wrong", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx", - "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", - " pm.response.to.have.status(401);", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Cookie", - "value": "Cookie_1=value" - } - ], - "body": { - "mode": "raw", - "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" - }, - "url": { - "raw": "{{baseUrl}}/user/v2/signin?token_only=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "user", - "v2", - "signin" - ], - "query": [ - { - "key": "token_only", - "value": "true" - } - ] - } - }, - "response": [] - } - ] - } - ] - } - ], - "info": { - "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", - "name": "users", - "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "26710321" - }, - "variable": [ - { - "key": "baseUrl", - "value": "", - "type": "string" - }, - { - "key": "admin_api_key", - "value": "", - "type": "string" - }, - { - "key": "api_key", - "value": "", - "type": "string" - }, - { - "key": "merchant_id", - "value": "" - }, - { - "key": "payment_id", - "value": "" - }, - { - "key": "customer_id", - "value": "" - }, - { - "key": "mandate_id", - "value": "" - }, - { - "key": "payment_method_id", - "value": "" - }, - { - "key": "refund_id", - "value": "" - }, - { - "key": "merchant_connector_id", - "value": "" - }, - { - "key": "client_secret", - "value": "", - "type": "string" - }, - { - "key": "connector_api_key", - "value": "", - "type": "string" - }, - { - "key": "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" - }, - { - "key": "connector_api_secret", - "value": "", - "type": "string" - }, - { - "key": "connector_key1", - "value": "", - "type": "string" - }, - { - "key": "connector_key2", - "value": "", - "type": "string" - }, - { - "key": "user_email", - "value": "", - "type": "string" - }, - { - "key": "user_password", - "value": "", - "type": "string" - }, - { - "key": "wrong_password", - "value": "", - "type": "string" - }, - { - "key": "user_base_email_for_signup", - "value": "", - "type": "string" - }, - { - "key": "user_domain_for_signup", - "value": "", - "type": "string" - } - ] -} + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + }, + "item": [ + { + "name": "Health check", + "item": [ + { + "name": "New Request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "Sign Up", + "item": [ + { + "name": "Connect Account", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/connect_account - 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]::/user/connect_account - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"is_email_sent\");", + " pm.expect(jsonData.is_email_sent).to.be.true;", + "});", + "", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "", + "var baseEmail = pm.environment.get('user_base_email_for_signup');", + "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", + "", + "// Generate a unique email address", + "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", + "// Set the unique email address as an environment variable", + "pm.environment.set('unique_email', uniqueEmail);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{unique_email}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Sign In", + "item": [ + { + "name": "Signin", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status code is 4xx Bad Request", + "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - 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]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\" \n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "", + "// Validate status 4xx", + "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - 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]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\" \n}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + } + ] + } + ] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "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" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +} \ No newline at end of file
ci
log request id for user tests (#5159)
49a60bf14725d67bc4f8c5814dc5ca27b7f57712
2024-09-10 22:32:22
Sakil Mostak
feat(core): [Payouts] Add billing address to payout list (#5004)
false
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs index e514dbfb4c3..42037c3c2d9 100644 --- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs +++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs @@ -54,7 +54,12 @@ pub trait PayoutsInterface { _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< - Vec<(Payouts, PayoutAttempt, Option<diesel_models::Customer>)>, + Vec<( + Payouts, + PayoutAttempt, + Option<diesel_models::Customer>, + Option<diesel_models::Address>, + )>, errors::StorageError, >; diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 82128f98a52..85d5b78521f 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -6,6 +6,8 @@ pub mod transformers; pub mod validator; use std::{collections::HashSet, vec::IntoIter}; +#[cfg(feature = "olap")] +use api_models::payments as payment_enums; use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; #[cfg(feature = "payout_retry")] use common_enums::PayoutRetryType; @@ -33,6 +35,8 @@ use time::Duration; #[cfg(feature = "olap")] use crate::types::domain::behaviour::Conversion; +#[cfg(feature = "olap")] +use crate::types::PayoutActionData; use crate::{ core::{ errors::{ @@ -770,7 +774,9 @@ pub async fn payouts_list_core( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); - let collected_futures = payouts.into_iter().map(|payout| async { + let mut pi_pa_tuple_vec = PayoutActionData::new(); + + for payout in payouts { match db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, @@ -778,73 +784,80 @@ pub async fn payouts_list_core( storage_enums::MerchantStorageScheme::PostgresOnly, ) .await + .change_context(errors::ApiErrorResponse::InternalServerError) { - Ok(ref payout_attempt) => match payout.customer_id.clone() { - Some(ref customer_id) => { + Ok(payout_attempt) => { + let domain_customer = match payout.customer_id.clone() { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] - match db + Some(customer_id) => db .find_customer_by_customer_id_merchant_id( &(&state).into(), - customer_id, + &customer_id, merchant_id, &key_store, merchant_account.storage_scheme, ) .await - { - Ok(customer) => Ok((payout, payout_attempt.to_owned(), Some(customer))), - Err(err) => { + .map_err(|err| { let err_msg = format!( "failed while fetching customer for customer_id - {:?}", customer_id ); logger::warn!(?err, err_msg); - if err.current_context().is_db_not_found() { - Ok((payout, payout_attempt.to_owned(), None)) - } else { - Err(err - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable(err_msg)) - } - } - } - } - None => Ok((payout.to_owned(), payout_attempt.to_owned(), None)), - }, + }) + .ok(), + _ => None, + }; + + let payout_id_as_payment_id_type = + common_utils::id_type::PaymentId::wrap(payout.payout_id.clone()) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "payout_id contains invalid data".to_string(), + }) + .attach_printable("Error converting payout_id to PaymentId type")?; + + let payment_addr = payment_helpers::create_or_find_address_for_payment_by_request( + &state, + None, + payout.address_id.as_deref(), + merchant_id, + payout.customer_id.as_ref(), + &key_store, + &payout_id_as_payment_id_type, + merchant_account.storage_scheme, + ) + .await + .transpose() + .and_then(|addr| { + addr.map_err(|err| { + let err_msg = format!( + "billing_address missing for address_id : {:?}", + payout.address_id + ); + logger::warn!(?err, err_msg); + }) + .ok() + .map(payment_enums::Address::foreign_from) + }); + + pi_pa_tuple_vec.push(( + payout.to_owned(), + payout_attempt.to_owned(), + domain_customer, + payment_addr, + )); + } Err(err) => { let err_msg = format!( - "failed while fetching payout_attempt for payout_id - {}", - payout.payout_id.clone(), + "failed while fetching payout_attempt for payout_id - {:?}", + payout.payout_id ); logger::warn!(?err, err_msg); - Err(err - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable(err_msg)) } } - }); - - let pi_pa_tuple_vec: Result< - Vec<( - storage::Payouts, - storage::PayoutAttempt, - Option<domain::Customer>, - )>, - _, - > = join_all(collected_futures) - .await - .into_iter() - .collect::<Result< - Vec<( - storage::Payouts, - storage::PayoutAttempt, - Option<domain::Customer>, - )>, - _, - >>(); + } let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec - .change_context(errors::ApiErrorResponse::InternalServerError)? .into_iter() .map(ForeignFrom::foreign_from) .collect(); @@ -874,6 +887,7 @@ pub async fn payouts_filtered_list_core( storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, + Option<diesel_models::Address>, )> = db .filter_payouts_and_attempts( merchant_account.get_id(), @@ -883,30 +897,50 @@ pub async fn payouts_filtered_list_core( .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list); - let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, c)| async { - let domain_cust = c - .async_and_then(|cust| async { - domain::Customer::convert_back( - &(&state).into(), - cust, - &key_store.key, - key_store.merchant_id.clone().into(), - ) - .await - .map_err(|err| { - let msg = format!("failed to convert customer for id: {:?}", p.customer_id); - logger::warn!(?err, msg); + let data: Vec<api::PayoutCreateResponse> = + join_all(list.into_iter().map(|(p, pa, customer, address)| async { + let customer: Option<domain::Customer> = customer + .async_and_then(|cust| async { + domain::Customer::convert_back( + &(&state).into(), + cust, + &key_store.key, + key_store.merchant_id.clone().into(), + ) + .await + .map_err(|err| { + let msg = format!("failed to convert customer for id: {:?}", p.customer_id); + logger::warn!(?err, msg); + }) + .ok() }) - .ok() - }) - .await; - Some((p, pa, domain_cust)) - })) - .await - .into_iter() - .flatten() - .map(ForeignFrom::foreign_from) - .collect(); + .await; + + let payout_addr: Option<payment_enums::Address> = address + .async_and_then(|addr| async { + domain::Address::convert_back( + &(&state).into(), + addr, + &key_store.key, + key_store.merchant_id.clone().into(), + ) + .await + .map(ForeignFrom::foreign_from) + .map_err(|err| { + let msg = format!("failed to convert address for id: {:?}", p.address_id); + logger::warn!(?err, msg); + }) + .ok() + }) + .await; + + Some((p, pa, customer, payout_addr)) + })) + .await + .into_iter() + .flatten() + .map(ForeignFrom::foreign_from) + .collect(); let active_payout_ids = db .filter_active_payout_ids_by_constraints(merchant_account.get_id(), &constraints) diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs index 35919abb1f0..ed17eb71afa 100644 --- a/crates/router/src/core/payouts/transformers.rs +++ b/crates/router/src/core/payouts/transformers.rs @@ -9,7 +9,7 @@ use common_utils::link_utils::EnabledPaymentMethod; ))] use crate::types::transformers::ForeignInto; #[cfg(feature = "olap")] -use crate::types::{domain, storage}; +use crate::types::{api::payments, domain, storage}; use crate::{ settings::PayoutRequiredFields, types::{api, transformers::ForeignFrom}, @@ -21,6 +21,7 @@ impl storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, + Option<payments::Address>, )> for api::PayoutCreateResponse { fn foreign_from( @@ -28,6 +29,7 @@ impl storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, + Option<payments::Address>, ), ) -> Self { todo!() @@ -44,6 +46,7 @@ impl storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, + Option<payments::Address>, )> for api::PayoutCreateResponse { fn foreign_from( @@ -51,9 +54,10 @@ impl storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, + Option<payments::Address>, ), ) -> Self { - let (payout, payout_attempt, customer) = item; + let (payout, payout_attempt, customer, address) = item; let attempt = api::PayoutAttemptResponse { attempt_id: payout_attempt.payout_attempt_id, status: payout_attempt.status, @@ -95,7 +99,7 @@ impl connector_transaction_id: attempt.connector_transaction_id.clone(), priority: payout.priority, attempts: Some(vec![attempt]), - billing: None, + billing: address, client_secret: None, payout_link: None, email: customer diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 2faa69978cb..acbb6fe04d2 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1521,7 +1521,7 @@ impl GetProfileId for storage::Payouts { } } #[cfg(feature = "payouts")] -impl<T, F> GetProfileId for (storage::Payouts, T, F) { +impl<T, F, R> GetProfileId for (storage::Payouts, T, F, R) { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.0.get_profile_id() } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9c625f1f2b5..2088177754e 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2073,6 +2073,7 @@ impl PayoutsInterface for KafkaStore { storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, + Option<diesel_models::Address>, )>, errors::DataStorageError, > { diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index a77f3a16adb..16a8ed1ccc4 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -207,6 +207,14 @@ pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; pub type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; +#[cfg(feature = "payouts")] +pub type PayoutActionData = Vec<( + storage::Payouts, + storage::PayoutAttempt, + Option<domain::Customer>, + Option<api_models::payments::Address>, +)>; + #[cfg(feature = "payouts")] pub trait PayoutIndividualDetailsExt { type Error; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 5d8c8a87bd2..741a7d89d5c 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -789,6 +789,52 @@ impl<'a> From<&'a domain::Address> for api_types::Address { } } +impl ForeignFrom<domain::Address> for api_types::Address { + fn foreign_from(address: domain::Address) -> Self { + // 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() + && address.line3.is_none() + && address.state.is_none() + && address.country.is_none() + && address.zip.is_none() + && address.first_name.is_none() + && address.last_name.is_none() + { + None + } else { + Some(api_types::AddressDetails { + city: address.city.clone(), + country: address.country, + line1: address.line1.clone().map(Encryptable::into_inner), + line2: address.line2.clone().map(Encryptable::into_inner), + line3: address.line3.clone().map(Encryptable::into_inner), + state: address.state.clone().map(Encryptable::into_inner), + zip: address.zip.clone().map(Encryptable::into_inner), + first_name: address.first_name.clone().map(Encryptable::into_inner), + last_name: address.last_name.clone().map(Encryptable::into_inner), + }) + }; + + // 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), + } + } +} + impl ForeignFrom<( diesel_models::api_keys::ApiKey, diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs index c151e8acb88..5f2cc8824e5 100644 --- a/crates/storage_impl/src/mock_db/payouts.rs +++ b/crates/storage_impl/src/mock_db/payouts.rs @@ -69,8 +69,15 @@ impl PayoutsInterface for MockDb { _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, - ) -> CustomResult<Vec<(Payouts, PayoutAttempt, Option<diesel_models::Customer>)>, StorageError> - { + ) -> CustomResult< + Vec<( + Payouts, + PayoutAttempt, + Option<diesel_models::Customer>, + Option<diesel_models::Address>, + )>, + StorageError, + > { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 3a5cc2854ee..7307de7c3f6 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -19,12 +19,18 @@ use diesel::{associations::HasTable, ExpressionMethods, NullableExpressionMethod not(feature = "customer_v2") ))] use diesel_models::payout_attempt::PayoutAttempt as DieselPayoutAttempt; +#[cfg(all( + feature = "olap", + any(feature = "v1", feature = "v2"), + not(feature = "customer_v2") +))] +use diesel_models::schema::{ + address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl, +}; #[cfg(feature = "olap")] use diesel_models::{ - customers::Customer as DieselCustomer, - enums as storage_enums, - query::generics::db_metrics, - schema::{customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl, payouts::dsl as po_dsl}, + address::Address as DieselAddress, customers::Customer as DieselCustomer, + enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, @@ -57,8 +63,8 @@ use crate::connection; not(feature = "customer_v2") ))] use crate::store::schema::{ - customers::all_columns as cust_all_columns, payout_attempt::all_columns as poa_all_columns, - payouts::all_columns as po_all_columns, + address::all_columns as addr_all_columns, customers::all_columns as cust_all_columns, + payout_attempt::all_columns as poa_all_columns, payouts::all_columns as po_all_columns, }; use crate::{ diesel_error_to_data_error, @@ -331,8 +337,15 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError> - { + ) -> error_stack::Result< + Vec<( + Payouts, + PayoutAttempt, + Option<DieselCustomer>, + Option<DieselAddress>, + )>, + StorageError, + > { self.router_store .filter_payouts_and_attempts(merchant_id, filters, storage_scheme) .await @@ -571,8 +584,17 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError> - { + ) -> error_stack::Result< + Vec<( + Payouts, + PayoutAttempt, + Option<DieselCustomer>, + Option<DieselAddress>, + )>, + StorageError, + > { + use common_utils::errors::ReportSwitchExt; + let conn = connection::pg_connection_read(self).await.switch()?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPayouts::table() @@ -585,6 +607,10 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)), ) .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned())) + .left_outer_join( + diesel_models::schema::address::table + .on(add_dsl::address_id.nullable().eq(po_dsl::address_id)), + ) .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); @@ -675,17 +701,28 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query - .select((po_all_columns, poa_all_columns, cust_all_columns.nullable())) - .get_results_async::<(DieselPayouts, DieselPayoutAttempt, Option<DieselCustomer>)>(conn) + .select(( + po_all_columns, + poa_all_columns, + cust_all_columns.nullable(), + addr_all_columns.nullable(), + )) + .get_results_async::<( + DieselPayouts, + DieselPayoutAttempt, + Option<DieselCustomer>, + Option<DieselAddress>, + )>(conn) .await .map(|results| { results .into_iter() - .map(|(pi, pa, c)| { + .map(|(pi, pa, c, add)| { ( Payouts::from_storage_model(pi), PayoutAttempt::from_storage_model(pa), c, + add, ) }) .collect() @@ -706,8 +743,15 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { _merchant_id: &common_utils::id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError> - { + ) -> error_stack::Result< + Vec<( + Payouts, + PayoutAttempt, + Option<DieselCustomer>, + Option<DieselAddress>, + )>, + StorageError, + > { todo!() }
feat
[Payouts] Add billing address to payout list (#5004)
46f77d078b8ea1e9234464d6065ce82aec63adfe
2023-02-25 18:22:01
Jagan
refactor(connector): remove `peek()` on PII info (#642)
false
diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index a5ab4103f52..96411d4632b 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -59,6 +59,28 @@ where masking_strategy: PhantomData, } } + + /// Zip 2 secrets with the same masking strategy into one + pub fn zip<OtherSecretValue>( + self, + other: Secret<OtherSecretValue, MaskingStrategy>, + ) -> Secret<(SecretValue, OtherSecretValue), MaskingStrategy> + where + MaskingStrategy: Strategy<OtherSecretValue> + Strategy<(SecretValue, OtherSecretValue)>, + { + (self.inner_secret, other.inner_secret).into() + } + + /// consume self and modify the inner value + pub fn map<OtherSecretValue>( + self, + f: impl FnOnce(SecretValue) -> OtherSecretValue, + ) -> Secret<OtherSecretValue, MaskingStrategy> + where + MaskingStrategy: Strategy<OtherSecretValue>, + { + f(self.inner_secret).into() + } } impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue> diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 2f681a72f76..ffab313bde6 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -1,12 +1,12 @@ use std::str::FromStr; use error_stack::report; +use masking::Secret; use serde::{Deserialize, Serialize}; use super::result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES}; use crate::{ core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, }; @@ -62,15 +62,15 @@ pub enum PaymentDetails { #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct CardDetails { #[serde(rename = "card.number")] - pub card_number: String, + pub card_number: Secret<String, common_utils::pii::CardNumber>, #[serde(rename = "card.holder")] - pub card_holder: String, + pub card_holder: Secret<String>, #[serde(rename = "card.expiryMonth")] - pub card_expiry_month: String, + pub card_expiry_month: Secret<String>, #[serde(rename = "card.expiryYear")] - pub card_expiry_year: String, + pub card_expiry_year: Secret<String>, #[serde(rename = "card.cvv")] - pub card_cvv: String, + pub card_cvv: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] @@ -100,13 +100,13 @@ pub enum AciPaymentType { impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_details: PaymentDetails = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => PaymentDetails::Card(CardDetails { - card_number: ccard.card_number.peek().clone(), - card_holder: ccard.card_holder_name.peek().clone(), - card_expiry_month: ccard.card_exp_month.peek().clone(), - card_expiry_year: ccard.card_exp_year.peek().clone(), - card_cvv: ccard.card_cvc.peek().clone(), + let payment_details: PaymentDetails = match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => PaymentDetails::Card(CardDetails { + card_number: ccard.card_number, + card_holder: ccard.card_holder_name, + card_expiry_month: ccard.card_exp_month, + card_expiry_year: ccard.card_exp_year, + card_cvv: ccard.card_cvc, }), api::PaymentMethod::BankTransfer => PaymentDetails::BankAccount(BankDetails { account_holder: "xyz".to_string(), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 027ecd30c92..b0a744d1287 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -5,7 +5,6 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::RefundsRequestData, core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, utils::OptionExt, }; @@ -71,12 +70,14 @@ impl From<api_models::payments::PaymentMethod> for PaymentDetails { fn from(value: api_models::payments::PaymentMethod) -> Self { match value { api::PaymentMethod::Card(ref ccard) => { - let expiry_month = ccard.card_exp_month.peek().clone(); - let expiry_year = ccard.card_exp_year.peek().clone(); - Self::CreditCard(CreditCardDetails { card_number: ccard.card_number.clone(), - expiration_date: format!("{expiry_year}-{expiry_month}").into(), + // expiration_date: format!("{expiry_year}-{expiry_month}").into(), + expiration_date: ccard + .card_exp_month + .clone() + .zip(ccard.card_exp_year.clone()) + .map(|(expiry_month, expiry_year)| format!("{expiry_year}-{expiry_month}")), card_code: Some(ccard.card_cvc.clone()), }) } diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 09962ecd78a..cd116779de3 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1,12 +1,12 @@ use api_models::payments; use base64::Engine; use error_stack::ResultExt; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ consts, core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, utils::OptionExt, }; @@ -79,10 +79,10 @@ pub struct Card { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CardDetails { - number: String, - expiration_month: String, - expiration_year: String, - cvv: String, + number: Secret<String, common_utils::pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + cvv: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { @@ -100,13 +100,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { }; let kind = "sale".to_string(); - let payment_method_data_type = match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => Ok(PaymentMethodType::CreditCard(Card { + let payment_method_data_type = match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card { credit_card: CardDetails { - number: ccard.card_number.peek().clone(), - expiration_month: ccard.card_exp_month.peek().clone(), - expiration_year: ccard.card_exp_year.peek().clone(), - cvv: ccard.card_cvc.peek().clone(), + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + cvv: ccard.card_cvc, }, })), api::PaymentMethod::Wallet(ref wallet_data) => { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 23f555d3646..6dfe630ccfe 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -41,10 +41,10 @@ pub struct PaymentInformation { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - number: String, - expiration_month: String, - expiration_year: String, - security_code: String, + number: Secret<String, pii::CardNumber>, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + security_code: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -107,8 +107,8 @@ fn build_bill_to( impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => { let phone = item.get_billing_phone()?; let phone_number = phone.get_number()?; let country_code = phone.get_country_code()?; @@ -131,10 +131,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest let payment_information = PaymentInformation { card: Card { - number: ccard.card_number.peek().clone(), - expiration_month: ccard.card_exp_month.peek().clone(), - expiration_year: ccard.card_exp_year.peek().clone(), - security_code: ccard.card_cvc.peek().clone(), + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, }, }; diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 580dd3fccc3..61844e64e3e 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -596,12 +596,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; - types::ResponseRouterData { + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, - } - .try_into() + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index dd4c2f3c3d1..e496d7477ed 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -1,3 +1,5 @@ +use common_utils::pii; +use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Serialize)] @@ -298,18 +300,18 @@ pub struct Card { /// did not work as expected. pub chip_condition: Option<ChipCondition>, /// The numeric value printed on the physical card. - pub cvv: String, + pub cvv: Secret<String>, /// Card Verification Value Indicator sent by the Merchant indicating the CVV /// availability. pub cvv_indicator: CvvIndicator, /// The 2 digit expiry date month of the card. - pub expiry_month: String, + pub expiry_month: Secret<String>, /// The 2 digit expiry date year of the card. - pub expiry_year: String, + pub expiry_year: Secret<String>, /// Indicates whether the card is a debit or credit card. pub funding: Option<Funding>, /// The the card account number used to authorize the transaction. Also known as PAN. - pub number: String, + pub number: Secret<String, pii::CardNumber>, /// Contains the pin block info, relating to the pin code the Payer entered. pub pin_block: Option<String>, /// The full card tag data for an EMV/chip card transaction. diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 717cd1e9efd..258d066629e 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -27,6 +27,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { .map(|o| o.to_string()) .ok_or_else(utils::missing_field_err("connector_meta.account_name"))?; let card = item.get_card()?; + let expiry_year = card.get_card_expiry_year_2_digit(); Ok(Self { account_name, amount: Some(item.request.amount.to_string()), @@ -39,10 +40,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { }), payment_method: requests::PaymentMethod { card: Some(requests::Card { - number: card.get_card_number(), - expiry_month: card.get_card_expiry_month(), - expiry_year: card.get_card_expiry_year_2_digit(), - cvv: card.get_card_cvc(), + number: card.card_number, + expiry_month: card.card_exp_month, + expiry_year, + cvv: card.card_cvc, ..Default::default() }), ..Default::default() diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index bb744fe0679..76370d53c08 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -1,8 +1,8 @@ +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ core::errors, - pii::PeekInterface, types::{self, api, storage::enums}, }; @@ -22,17 +22,17 @@ pub struct DeviceData; #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { - number: String, - exp_month: String, - exp_year: String, - cardholder_name: String, + number: Secret<String, common_utils::pii::CardNumber>, + exp_month: Secret<String>, + exp_year: Secret<String>, + cardholder_name: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { - api::PaymentMethod::Card(ref ccard) => { + match item.request.payment_method_data.clone() { + api::PaymentMethod::Card(ccard) => { let submit_for_settlement = matches!( item.request.capture_method, Some(enums::CaptureMethod::Automatic) | None @@ -40,10 +40,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for Shift4PaymentsRequest { let payment_request = Self { amount: item.request.amount.to_string(), card: Card { - number: ccard.card_number.peek().clone(), - exp_month: ccard.card_exp_month.peek().clone(), - exp_year: ccard.card_exp_year.peek().clone(), - cardholder_name: ccard.card_holder_name.peek().clone(), + number: ccard.card_number, + exp_month: ccard.card_exp_month, + exp_year: ccard.card_exp_year, + cardholder_name: ccard.card_holder_name, }, currency: item.request.currency.to_string(), description: item.description.clone(), diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 605822a96c9..bab9d21cd1c 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -94,29 +94,14 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData { } pub trait CardData { - fn get_card_number(&self) -> String; - fn get_card_expiry_month(&self) -> String; - fn get_card_expiry_year(&self) -> String; - fn get_card_expiry_year_2_digit(&self) -> String; - fn get_card_cvc(&self) -> String; + fn get_card_expiry_year_2_digit(&self) -> Secret<String>; } impl CardData for api::Card { - fn get_card_number(&self) -> String { - self.card_number.peek().clone() - } - fn get_card_expiry_month(&self) -> String { - self.card_exp_month.peek().clone() - } - fn get_card_expiry_year(&self) -> String { - self.card_exp_year.peek().clone() - } - fn get_card_expiry_year_2_digit(&self) -> String { - let year = self.card_exp_year.peek().clone(); - year[year.len() - 2..].to_string() - } - fn get_card_cvc(&self) -> String { - self.card_cvc.peek().clone() + fn get_card_expiry_year_2_digit(&self) -> Secret<String> { + let binding = self.card_exp_year.clone(); + let year = binding.peek(); + Secret::new(year[year.len() - 2..].to_string()) } } pub trait PhoneDetailsData { diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index a76b02d7cfd..757942a5354 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -1,3 +1,5 @@ +use common_utils::pii; +use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -148,10 +150,10 @@ pub struct CardPayment { pub card_holder_name: Option<String>, pub card_expiry_date: CardExpiryDate, #[serde(skip_serializing_if = "Option::is_none")] - pub cvc: Option<String>, + pub cvc: Option<Secret<String>>, #[serde(rename = "type")] pub payment_type: PaymentType, - pub card_number: String, + pub card_number: Secret<String, pii::CardNumber>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -174,8 +176,8 @@ pub struct WalletPayment { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct CardExpiryDate { - pub month: u8, - pub year: u16, + pub month: Secret<String>, + pub year: Secret<String>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 19b297b0d15..de160756842 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -1,8 +1,5 @@ -use std::str::FromStr; - use common_utils::errors::CustomResult; use error_stack::ResultExt; -use masking::PeekInterface; use storage_models::enums; use super::{requests::*, response::*}; @@ -12,30 +9,16 @@ use crate::{ utils::OptionExt, }; -fn parse_int<T: FromStr>( - val: masking::Secret<String, masking::WithType>, -) -> CustomResult<T, errors::ConnectorError> -where - <T as FromStr>::Err: Sync, -{ - let res = val.peek().parse::<T>(); - if let Ok(val) = res { - Ok(val) - } else { - Err(errors::ConnectorError::RequestEncodingFailed)? - } -} - fn fetch_payment_instrument( payment_method: api::PaymentMethod, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { api::PaymentMethod::Card(card) => Ok(PaymentInstrument::Card(CardPayment { card_expiry_date: CardExpiryDate { - month: parse_int::<u8>(card.card_exp_month)?, - year: parse_int::<u16>(card.card_exp_year)?, + month: card.card_exp_month, + year: card.card_exp_year, }, - card_number: card.card_number.peek().to_string(), + card_number: card.card_number, ..CardPayment::default() })), api::PaymentMethod::Wallet(wallet) => match wallet.issuer_name { diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index e4adf876737..1aa55720e32 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -88,6 +88,7 @@ pub enum ApiErrorResponse { message: String, connector: String, status_code: u16, + reason: Option<String>, }, #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")] PaymentAuthorizationFailed { data: Option<serde_json::Value> }, @@ -340,8 +341,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon code, message, connector, + reason, status_code, - } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), + } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.clone(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6f8761363ed..5dc58a076d3 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -68,6 +68,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData message: error_response.message, connector, status_code: error_response.status_code, + reason: error_response.reason, }) }) })?; @@ -126,6 +127,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData> message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -166,6 +168,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData> message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -205,6 +208,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> f message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; @@ -249,6 +253,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::VerifyRequestData> fo message: error_response.message, code: error_response.code, status_code: error_response.status_code, + reason: error_response.reason, connector, } })?; diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index 971f42f3bcb..204c300ca2f 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -1,5 +1,3 @@ -use std::{thread::sleep, time::Duration}; - use masking::Secret; use router::types::{ self, @@ -54,6 +52,10 @@ fn get_default_payment_info() -> Option<PaymentInfo> { }), ..Default::default() }), + access_token: Some(types::AccessToken { + token: "<access_token>".to_string(), + expires: 18600, + }), ..Default::default() }) } @@ -100,7 +102,6 @@ async fn should_sync_payment() { .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); - sleep(Duration::from_secs(5)); // to avoid 404 error as globalpay takes some time to process the new transaction let response = connector .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, @@ -111,7 +112,7 @@ async fn should_sync_payment() { encoded_data: None, capture_method: None, }), - None, + get_default_payment_info(), ) .await .unwrap();
refactor
remove `peek()` on PII info (#642)
92c776714f63d02055fc46b5b750cee71328f5eb
2023-06-15 13:21:25
shubhanshu-mani
test(postman-collection): Add Github action to run postman collection (#1272)
false
diff --git a/.github/workflows/postman-collection-runner.yml b/.github/workflows/postman-collection-runner.yml new file mode 100644 index 00000000000..c963e064449 --- /dev/null +++ b/.github/workflows/postman-collection-runner.yml @@ -0,0 +1,39 @@ +name: Postman Collection API test + +on: + schedule: + # Run workflow at 6 AM and 6 PM IST + - cron: "30 0,12 * * *" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + api_tests: + name: Run Postman Collection on integ env + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Not installing the newman since it's already included in the Ubuntu image. + #- name: Install Newman + # run: npm install -g newman + + # - name: Install portman + # run: npm install -g @apideck/portman + + # - name: Generate postman collection + # run: portman --cliOptionsFile postman/portman-cli.json + + run_api_test_stripe: + name: Run Postman Collection + runs-on: ubuntu-latest + needs: api_tests + steps: + - name: Run Newman + run: + newman run postman/hyperswitch.postman_collection.json --env-var admin_api_key=${{ secrets.INTEG_ADMIN_API_KEY }} --env-var baseUrl=${{ secrets.INTEG_BASE_URL }} --env-var connector_api_key=${{ secrets.STRIPE_API_KEY }} + --env-var gateway_merchant_id=${{ secrets.STRIPE_GATEWAY_MERCHANT_ID }} --env-var certificate=${{ secrets.STRIPE_GPAY_CERTIFICATE }} --env-var certificate_keys=${{ secrets.STRIPE_GPAY_CERTIFICATE_KEYS }} diff --git a/postman/hyperswitch.postman_collection.json b/postman/hyperswitch.postman_collection.json new file mode 100644 index 00000000000..b9055abdb67 --- /dev/null +++ b/postman/hyperswitch.postman_collection.json @@ -0,0 +1,14019 @@ +{ + "info": { + "_postman_id": "faf79340-e864-41f2-afe8-c87d2b593060", + "name": "HyperSwitch APIs", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "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": "MerchantAccounts", + "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" + } + } + ], + "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": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "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": "Merchant Account - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/accounts/: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 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" + } + } + ], + "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": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Retrieve a merchant account details." + }, + "response": [] + }, + { + "name": "Merchant Account - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts/: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 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" + } + } + ], + "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": "{\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_name\": \"NewAge Retailer\",\n \"locker_id\": \"m0010\",\n \"merchant_details\": {\n \"primary_contact_person\": \"joseph Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"veniam aute officia ullamco esse\",\n \"secondary_contact_person\": \"joseph Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"proident adipisicing officia nulla\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "To update an existing merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" + }, + "response": [] + } + ] + }, + { + "name": "API Key", + "item": [ + { + "name": "Create API Key", + "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Update API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_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/:api_key_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": "{\n \"name\": null,\n \"description\": \"My very awesome API key\",\n \"expiration\": null\n}" + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api_key_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api_key_id", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Retrieve API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_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": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api_key_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api_key_id", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "List API Keys", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/api_keys/:merchant_id/list - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/api_keys/:merchant_id/list - 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": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/list", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + "list" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Delete API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api-key", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api-key" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api-key", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "PaymentConnectors", + "item": [ + { + "name": "Payment Connector - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/accounts/:account_id/connectors - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts/: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" + } + } + ], + "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\":\"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "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": "Payment Connector - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_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 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" + } + } + ], + "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": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}", + "description": "(Required) The unique identifier for the payment connector" + } + ] + }, + "description": "Retrieve Payment Connector details." + }, + "response": [] + }, + { + "name": "Payment Connector - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - 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/:connector_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 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" + } + } + ], + "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}" + } + ] + }, + "description": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" + }, + "response": [] + }, + { + "name": "List Connectors by MID", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/account/:account_id/connectors - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/account/:account_id/connectors - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Payment Connector - Delete", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_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 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" + } + } + ], + "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": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}" + } + ] + }, + "description": "Delete or Detach a Payment Connector from Merchant Account" + }, + "response": [] + }, + { + "name": "Merchant Account - Delete", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/accounts/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Response Validation", + "const schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\",\"deleted\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the MerchantAccount object.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"deleted\":{\"type\":\"boolean\",\"description\":\"Indicates the deletion status of the Merchant Account object.\",\"example\":true}}}", + "", + "// Validate if response matches JSON schema ", + "pm.test(\"[DELETE]::/accounts/:id - Schema is valid\", function() {", + " pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});", + "});", + "" + ], + "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": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Delete a Merchant Account" + }, + "response": [] + } + ] + }, + { + "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" + } + } + ], + "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": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" + }, + "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" + } + } + ], + "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"affirm\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"afterpay_clearpay\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"invoke_sdk_client\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_debit\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"becs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_transfer\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"bacs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"apple_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"google_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"google_pay\": {\n \"allowed_payment_methods\": [\n {\n \"type\": \"CARD\",\n \"parameters\": {\n \"allowed_auth_methods\": [\n \"PAN_ONLY\",\n \"CRYPTOGRAM_3DS\"\n ],\n \"allowed_card_networks\": [\n \"AMEX\",\n \"DISCOVER\",\n \"INTERAC\",\n \"JCB\",\n \"MASTERCARD\",\n \"VISA\"\n ]\n },\n \"tokenization_specification\": {\n \"type\": \"PAYMENT_GATEWAY\",\n \"parameters\": {\n \"gateway\": \"example\",\n \"gateway_merchant_id\": \"{{gateway_merchant_id}}\"\n }\n }\n }\n ],\n \"merchant_info\": {\n \"merchant_name\": \"Narayan Bhat\"\n }\n },\n \"apple_pay\": {\n \"session_token_data\": {\n \"initiative\": \"web\",\n \"certificate\": \"{{certificate}}\",\n \"display_name\": \"applepay\",\n \"certificate_keys\": \"{{certificate_keys}}\",\n \"initiative_context\": \"hyperswitch-sdk-test.netlify.app\",\n \"merchant_identifier\": \"merchant.com.stripe.sang\"\n },\n \"payment_request_data\": {\n \"label\": \"applepay pvt.ltd\",\n \"supported_networks\": [\n \"visa\",\n \"masterCard\",\n \"amex\",\n \"discover\"\n ],\n \"merchant_capabilities\": [\n \"supports3DS\"\n ]\n }\n }\n }\n}", + "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": [ + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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.');", + "};", + "" + ], + "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\": 600,\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", + "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": "Customers", + "item": [ + { + "name": "Create Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/customers - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/customers - 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]::/customers - 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 \"customer_id\"", + "pm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {", + " pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have a minimum length of \"1\" for \"customer_id\"", + "if (jsonData?.customer_id) {", + "pm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {", + " pm.expect(jsonData.customer_id.length).is.at.least(1);", + "})};", + "", + "", + "// 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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"First customer\",\n \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}}/customers", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers" + ] + }, + "description": "Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details." + }, + "response": [] + }, + { + "name": "Retrieve Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/customers/: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]::/customers/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Retrieve a customer's details." + }, + "response": [] + }, + { + "name": "Update Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/customers/: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]::/customers/:id - 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", + "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"888888888\",\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Updates the customer's details in a customer object." + }, + "response": [] + }, + { + "name": "Ephemeral Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/ephemeral_keys - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"customer_id\": \"{{customer_id}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/ephemeral_keys", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "ephemeral_keys" + ] + } + }, + "response": [] + }, + { + "name": "Delete Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/customers/: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(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Delete a customer record." + }, + "response": [] + } + ], + "description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods." + }, + { + "name": "Payments", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Session Token", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments/session_tokens - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/session_tokens - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{publishable_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"wallets\":[],\n \"client_secret\": \"{{client_secret}}\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/payments/session_tokens", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + "session_tokens" + ] + } + }, + "response": [] + }, + { + "name": "Payments - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// 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();", + "});", + "", + "", + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 20000,\n \"currency\": \"SGD\",\n \"confirm\" :false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"email\": \"[email protected]\",\n \"name\": \"joseph Doe\",\n \"phone\": \"8888888888\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"return_url\": \"https://google.com\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "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 " + }, + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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\");", + "});", + "", + "", + "", + "// 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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": " {}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 6540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 - Create Copy", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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", + "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();", + "});", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "response": [] + }, + { + "name": "Payment-List", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/payments/list - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/list - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "api-key", + "value": "snd_0b8e1deb82f241eca47617afb1398858" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/list", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + "list" + ], + "query": [ + { + "key": "customer_id", + "value": "", + "disabled": true + }, + { + "key": "starting_after", + "value": "", + "disabled": true + }, + { + "key": "ending_before", + "value": "", + "disabled": true + }, + { + "key": "limit", + "value": "100", + "disabled": true + }, + { + "key": "created", + "value": "", + "disabled": true + }, + { + "key": "created.lt", + "value": "", + "disabled": true + }, + { + "key": "created.gt", + "value": "", + "disabled": true + }, + { + "key": "created.lte", + "value": "", + "disabled": true + }, + { + "key": "created_gte", + "value": "", + "disabled": true + } + ] + } + }, + "response": [] + } + ], + "description": "Process and manage payments across wide range of payment processors using the Unified Payments API." + }, + { + "name": "Refunds", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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.');", + "};", + "" + ], + "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\": 600,\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 - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/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": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"reason\": \"Paid by mistake\",\n \"metadata\": {\n \"udf1\": \"value2\",\n \"new_customer\": \"false\",\n \"login_date\": \"2019-09-1T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" + }, + "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", + "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": "PaymentMethods", + "item": [ + { + "name": "PaymentMethods - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payment_methods - 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_method_id as variable for jsonData.payment_method_id", + "if (jsonData?.payment_method_id) {", + " pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);", + " console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id 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", + "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_issuer\": \"Visa\",\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"customer_id\": \"cus_mnewerunwiuwiwqw\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payment_methods", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payment_methods" + ] + }, + "description": "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" + }, + "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\");", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/payment_methods", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + "payment_methods" + ], + "query": [ + { + "key": "client_secret", + "value": "{{client_secret}}", + "disabled": true + } + ] + }, + "description": "To filter and list the applicable payment methods for a particular merchant id." + }, + "response": [] + }, + { + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 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": "PaymentMethods - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payment_methods/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payment_methods/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payment_methods/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payment_methods", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_method_id}}", + "description": "(Required) The unique identifier for the payment method" + } + ] + }, + "description": "To update an existing a payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards, to prevent discontinuity in recurring payments" + }, + "response": [] + }, + { + "name": "Delete PaymentMethods", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payment_methods/:id/detach - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payment_methods/:id/detach - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payment_methods/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payment_methods", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_token}}", + "description": "(Required) The unique identifier for the payment method" + } + ] + }, + "description": "Detaches a PaymentMethod object from a Customer." + }, + "response": [] + } + ] + }, + { + "name": "Hackathon", + "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" + } + } + ], + "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": "{\n \"merchant_id\": \"merchant_{{$timestamp}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://google.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", + "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" + }, + "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" + } + } + ], + "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"affirm\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"afterpay_clearpay\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"invoke_sdk_client\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_debit\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"becs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_transfer\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"bacs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"apple_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"google_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"google_pay\": {\n \"allowed_payment_methods\": [\n {\n \"type\": \"CARD\",\n \"parameters\": {\n \"allowed_auth_methods\": [\n \"PAN_ONLY\",\n \"CRYPTOGRAM_3DS\"\n ],\n \"allowed_card_networks\": [\n \"AMEX\",\n \"DISCOVER\",\n \"INTERAC\",\n \"JCB\",\n \"MASTERCARD\",\n \"VISA\"\n ]\n },\n \"tokenization_specification\": {\n \"type\": \"PAYMENT_GATEWAY\",\n \"parameters\": {\n \"gateway\": \"example\",\n \"gateway_merchant_id\": \"{{gateway_merchant_id}}\"\n }\n }\n }\n ],\n \"merchant_info\": {\n \"merchant_name\": \"Narayan Bhat\"\n }\n },\n \"apple_pay\": {\n \"session_token_data\": {\n \"initiative\": \"web\",\n \"certificate\": \"{{certificate}}\",\n \"display_name\": \"applepay\",\n \"certificate_keys\": \"{{certificate_keys}}\",\n \"initiative_context\": \"hyperswitch-sdk-test.netlify.app\",\n \"merchant_identifier\": \"merchant.com.stripe.sang\"\n },\n \"payment_request_data\": {\n \"label\": \"applepay pvt.ltd\",\n \"supported_networks\": [\n \"visa\",\n \"masterCard\",\n \"amex\",\n \"discover\"\n ],\n \"merchant_capabilities\": [\n \"supports3DS\"\n ]\n }\n }\n }\n}", + "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": [ + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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.');", + "};", + "" + ], + "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\": 600,\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", + "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": "Happy Cases", + "item": [ + { + "name": "Scenario1-Create payment with confirm true", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "})};", + "" + ], + "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": "Scenario2-Create payment with confirm false", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// 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 \"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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": " {}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"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\");", + "})};" + ], + "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": "Scenario3-Create payment without PMD", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// 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 \"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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"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\");", + "})};" + ], + "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": "Scenario4-Create 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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - 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\");", + "})};", + "", + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 6000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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", + "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": "Scenario5-Void the payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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", + "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();", + "});", + "", + "// 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 \"cancelled\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\", function() {", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "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 \"cancelled\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\", function() {", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", + "})};" + ], + "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": "Scenario6-Create 3DS payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"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\");", + "})};", + "" + ], + "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": "Scenario7-Create 3DS payment with confrm false", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments/: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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": " {}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario9-Refund full payment", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "})};", + "" + ], + "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'\", 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "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\": 6540,\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.');", + "};", + "", + "// 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "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": "Scenario10-Partial refund", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "})};", + "" + ], + "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'\", 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);", + "})};", + "" + ], + "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\": 540,\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.');", + "};", + "", + "// 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 '540'\", function() {", + " pm.expect(jsonData.amount).to.eql(540);", + "})};", + "" + ], + "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": "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'\", function() {", + " pm.expect(jsonData.status).to.eql(\"succeeded\");", + "})};", + "", + "// 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);", + "})};", + "" + ], + "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\": 1000,\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.');", + "};", + "", + "// 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 '1000'\", function() {", + " pm.expect(jsonData.amount).to.eql(1000);", + "})};", + "" + ], + "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": "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 \"refunds\"", + "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function() {", + " pm.expect((typeof jsonData.refunds !== \"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-Create a mandate and recurring payment", + "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.');", + "};", + "", + "// 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\"", + "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\", 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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\", 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Scenario11-Refund recurring payment", + "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.');", + "};", + "", + "// 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\"", + "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\", 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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\"", + "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\", 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", + "raw": "{\n \"amount\": 6570,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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);", + "})};", + "" + ], + "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\": 6540,\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 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "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-BNPL-klarna", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 8000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"klarna_redirect\": {\n \"issuer_name\": \"stripe\",\n \"billing_email\": \"[email protected]\",\n \"billing_country\": \"US\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario13-BNPL-afterpay", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 7000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"country\": \"SE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"SE\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"order_details\": {\n \"product_name\": \"Socks\",\n \"amount\": 7000,\n \"quantity\": 1\n }\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'afterpay_clearpay'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"afterpay_clearpay_redirect\": {\n \"billing_name\": \"Akshaya\",\n \"billing_email\": \"[email protected]\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario14-BNPL-affirm", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 7000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"country\": \"US\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"order_details\": {\n \"product_name\": \"Socks\",\n \"amount\": 7000,\n \"quantity\": 1\n }\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'affirm'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"affirm_redirect\": {\n \"issuer_name\": \"affirm\",\n \"billing_email\": \"[email protected]\",\n \"billing_country\": \"US\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario15-Bank Redirect-Ideal", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'ideal'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"ideal\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"ideal\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"ing\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario16-Bank Redirect-sofort", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'sofort'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"sofort\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"sofort\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"hypo_noe_lb_fur_niederosterreich_u_wien\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario17-Bank Redirect-eps", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'eps'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"eps\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"eps\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"hypo_oberosterreich_salzburg_steiermark\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario18-Bank Redirect-giropay", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'giropay'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"giropay\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"giropay\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario19-Bank Transfer-ach", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 800,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 800,\n \"customer_id\": \"poll\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://hs-payments-test.netlify.app/payments\",\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_transfer\",\n \"payment_method_type\": \"ach\",\n \"payment_method_data\": {\n \"bank_transfer\": {\n \"ach_bank_transfer\": {\n \"billing_details\": {\n \"email\": \"[email protected]\"\n }\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario19-Bank Transfer-ach Copy 2", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 800,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 800,\n \"customer_id\": \"poll\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://hs-payments-test.netlify.app/payments\",\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\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}}/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;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"bank_transfer\",\n \"payment_method_type\": \"ach\",\n \"payment_method_data\": {\n \"bank_transfer\": {\n \"ach_bank_transfer\": {\n \"billing_details\": {\n \"email\": \"[email protected]\"\n }\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Variation Cases", + "item": [ + { + "name": "Scenario1-Create payment with Invalid card details", + "item": [ + { + "name": "Payments - Create(Invalid card number)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector_error'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector_error\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"123456\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"united states\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"united states\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 Exp month)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"01\",\n \"card_exp_year\": \"2023\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 Exp Year)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2022\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"123456\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"12345\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Scenario2-Confirming the payment without PMD", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": " {}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario3-Capture greater amount", + "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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 7000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"requires_capture\" 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\");", + "})};" + ], + "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": "Scenario4-Capture the succeeded payment", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 7000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario5-Void the success/failure payment", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 4xx ", + "pm.test(\"[POST]::/payments/:id/cancel - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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();", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "response": [] + } + ] + }, + { + "name": "Scenario6-Create 3DS payment with greater 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.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"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\");", + "})};" + ], + "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": "Payments - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount_to_capture\": 7540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario7-Refund exceeds amount", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", + "})};", + "" + ], + "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 4xx ", + "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "" + ], + "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\": 7000,\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": "Scenario8-Refund for unsuccessful payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "" + ], + "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 4xx ", + "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "" + ], + "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\": 540,\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": "Scenario9-Create a recurring payment with greater mandate amount", + "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.');", + "};", + "", + "// 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\"", + "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\", 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", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 8040,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://google.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "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" + } + ] +}
test
Add Github action to run postman collection (#1272)
59573efe91274b6986fcbe80b1c856ba5e1273bd
2023-01-10 15:06:34
Rachit Naithani
refactor(router): Refactored Authentication (#327)
false
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 552593d596d..ed211951ede 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -8,7 +8,7 @@ use crate::{ compatibility::{stripe::errors, wrap}, core::customers, routes, - services::api, + services::{api, authentication as auth}, types::api::customers as customer_types, }; @@ -44,7 +44,7 @@ pub async fn customer_create( |state, merchant_account, req| { customers::create_customer(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -75,7 +75,7 @@ pub async fn customer_retrieve( |state, merchant_account, req| { customers::retrieve_customer(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -115,7 +115,7 @@ pub async fn customer_update( |state, merchant_account, req| { customers::update_customer(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -144,7 +144,7 @@ pub async fn customer_delete( &req, payload, customers::delete_customer, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 56e58f181e6..eebffc5670c 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -9,7 +9,7 @@ use crate::{ compatibility::{stripe::errors, wrap}, core::payments, routes, - services::api, + services::{api, authentication as auth}, types::api::{self as api_types}, }; @@ -58,7 +58,7 @@ pub async fn payment_intents_create( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -78,11 +78,10 @@ pub async fn payment_intents_retrieve( param: None, }; - let auth_type = match api::get_auth_type(&req) { - Ok(auth_type) => auth_type, + let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; - let auth_flow = api::get_auth_flow(&auth_type); wrap::compatibility_api_wrap::< _, @@ -107,7 +106,7 @@ pub async fn payment_intents_retrieve( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -138,12 +137,11 @@ pub async fn payment_intents_update( payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), + let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), }; - let auth_flow = api::get_auth_flow(&auth_type); + wrap::compatibility_api_wrap::< _, _, @@ -168,7 +166,7 @@ pub async fn payment_intents_update( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -200,12 +198,12 @@ pub async fn payment_intents_confirm( payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), - }; - let auth_flow = api::get_auth_flow(&auth_type); + let (auth_type, auth_flow) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + wrap::compatibility_api_wrap::< _, _, @@ -230,7 +228,7 @@ pub async fn payment_intents_confirm( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -280,7 +278,7 @@ pub async fn payment_intents_capture( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -307,11 +305,11 @@ pub async fn payment_intents_cancel( let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into(); payload.payment_id = payment_id; - let auth_type = match api::get_auth_type(&req) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), + let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), }; - let auth_flow = api::get_auth_flow(&auth_type); + wrap::compatibility_api_wrap::< _, _, @@ -335,7 +333,7 @@ pub async fn payment_intents_cancel( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -366,7 +364,7 @@ pub async fn payment_intent_list( |state, merchant_account, req| { payments::list_payments(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 90fe7ee4387..f498893df24 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -7,7 +7,7 @@ use crate::{ compatibility::{stripe::errors, wrap}, core::refunds, routes, - services::api, + services::authentication as auth, types::api::refunds as refund_types, }; @@ -34,7 +34,7 @@ pub async fn refund_create( &req, create_refund_req, refunds::refund_create_core, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -67,7 +67,7 @@ pub async fn refund_retrieve( refunds::refund_retrieve_core, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -99,7 +99,7 @@ pub async fn refund_update( |state, merchant_account, req| { refunds::refund_update_core(&*state.store, merchant_account, &refund_id, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index 171fbb6b5ea..29f0b79453a 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -9,7 +9,7 @@ use crate::{ compatibility::{stripe::errors, wrap}, core::payments, routes, - services::api, + services::{api, authentication as auth}, types::api as api_types, }; @@ -55,7 +55,7 @@ pub async fn setup_intents_create( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -75,11 +75,10 @@ pub async fn setup_intents_retrieve( param: None, }; - let auth_type = match api::get_auth_type(&req) { - Ok(auth_type) => auth_type, + let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; - let auth_flow = api::get_auth_flow(&auth_type); wrap::compatibility_api_wrap::< _, @@ -104,7 +103,7 @@ pub async fn setup_intents_retrieve( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -131,12 +130,12 @@ pub async fn setup_intents_update( let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), - }; - let auth_flow = api::get_auth_flow(&auth_type); + let (auth_type, auth_flow) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + wrap::compatibility_api_wrap::< _, _, @@ -161,7 +160,7 @@ pub async fn setup_intents_update( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -189,12 +188,12 @@ pub async fn setup_intents_confirm( payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), - }; - let auth_flow = api::get_auth_flow(&auth_type); + let (auth_type, auth_flow) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + wrap::compatibility_api_wrap::< _, _, @@ -219,7 +218,7 @@ pub async fn setup_intents_confirm( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index a36d42414b4..4064304d248 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -8,28 +8,25 @@ use serde::Serialize; use crate::{ core::errors::{self, RouterResult}, routes, - services::{api, logger}, - types::storage, + services::{api, authentication as auth, logger}, }; -#[instrument(skip(request, payload, state, func))] -pub async fn compatibility_api_wrap<'a, 'b, A, T, Q, F, Fut, S, E>( +#[instrument(skip(request, payload, state, func, api_authentication))] +pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E>( state: &'b routes::AppState, request: &'a HttpRequest, payload: T, func: F, - api_authentication: A, + api_authentication: &dyn auth::AuthenticateAndFetch<U>, ) -> HttpResponse where - A: Into<api::ApiAuthentication<'a>> + std::fmt::Debug, - F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut, + F: Fn(&'b routes::AppState, U, T) -> Fut, Fut: Future<Output = RouterResult<api::BachResponse<Q>>>, Q: Serialize + std::fmt::Debug + 'a, S: From<Q> + Serialize, E: From<errors::ApiErrorResponse> + Serialize + error_stack::Context + actix_web::ResponseError, T: std::fmt::Debug, { - let api_authentication = api_authentication.into(); let resp = api::server_wrap_util(state, request, payload, func, api_authentication).await; match resp { Ok(api::BachResponse::Json(router_resp)) => { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 690175a229b..1a9ffaae862 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -593,37 +593,6 @@ pub(crate) async fn call_payment_method( } } -pub(crate) fn client_secret_auth<P>( - payload: P, - auth_type: &services::api::MerchantAuthentication<'_>, -) -> RouterResult<P> -where - P: services::Authenticate, -{ - match auth_type { - services::MerchantAuthentication::PublishableKey => { - payload - .get_client_secret() - .check_value_present("client_secret") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "client_secret".to_owned(), - })?; - Ok(payload) - } - services::api::MerchantAuthentication::ApiKey => { - if payload.get_client_secret().is_some() { - Err(report!(errors::ApiErrorResponse::InvalidRequestData { - message: "client_secret is not a valid parameter".to_owned(), - })) - } else { - Ok(payload) - } - } - _ => Err(report!(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unexpected Auth type")), - } -} - pub async fn get_customer_from_details( db: &dyn StorageInterface, customer_id: Option<String>, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index cfe0c691b30..7e14ec2eb56 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -2,7 +2,11 @@ use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -use crate::{core::admin::*, services::api, types::api::admin}; +use crate::{ + core::admin::*, + services::{api, authentication as auth}, + types::api::admin, +}; /// Merchant Account - Create /// @@ -28,7 +32,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req| create_merchant_account(&*state.store, req), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -49,7 +53,7 @@ pub async fn retrieve_merchant_account( &req, payload, |state, _, req| get_merchant_account(&*state.store, req), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -68,7 +72,7 @@ pub async fn update_merchant_account( &req, json_payload.into_inner(), |state, _, req| merchant_account_update(&*state.store, &merchant_id, req), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -89,7 +93,7 @@ pub async fn delete_merchant_account( &req, payload, |state, _, req| merchant_account_delete(&*state.store, req.merchant_id), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -109,7 +113,7 @@ pub async fn payment_connector_create( &req, json_payload.into_inner(), |state, _, req| create_payment_connector(&*state.store, req, &merchant_id), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -134,7 +138,7 @@ pub async fn payment_connector_retrieve( |state, _, req| { retrieve_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) }, - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -152,7 +156,7 @@ pub async fn payment_connector_list( &req, merchant_id, |state, _, merchant_id| list_payment_connectors(&*state.store, merchant_id), - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -173,7 +177,7 @@ pub async fn payment_connector_update( |state, _, req| { update_payment_connector(&*state.store, &merchant_id, merchant_connector_id, req) }, - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } @@ -198,7 +202,7 @@ pub async fn payment_connector_delete( |state, _, req| { delete_payment_connector(&*state.store, req.merchant_id, req.merchant_connector_id) }, - api::MerchantAuthentication::AdminApiKey, + &auth::AdminApiAuth, ) .await } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 08e2342a422..81038c41931 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -4,7 +4,7 @@ use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::customers::*, - services::{self, api}, + services::{api, authentication as auth}, types::api::customers, }; @@ -20,7 +20,7 @@ pub async fn customers_create( &req, json_payload.into_inner(), |state, merchant_account, req| create_customer(&*state.store, merchant_account, req), - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -36,22 +36,19 @@ pub async fn customers_retrieve( customer_id: path.into_inner(), }) .into_inner(); - let auth_type = match services::authenticate_eph_key( - &req, - &*state.store, - payload.customer_id.clone(), - ) - .await - { - Ok(auth_type) => auth_type, - Err(err) => return api::log_and_return_error_response(err), - }; + + let auth = + match auth::is_ephemeral_auth(req.headers(), &*state.store, &payload.customer_id).await { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + api::server_wrap( &state, &req, payload, |state, merchant_account, req| retrieve_customer(&*state.store, merchant_account, req), - auth_type, + &*auth, ) .await } @@ -71,7 +68,7 @@ pub async fn customers_update( &req, json_payload.into_inner(), |state, merchant_account, req| update_customer(&*state.store, merchant_account, req), - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -87,14 +84,7 @@ pub async fn customers_delete( customer_id: path.into_inner(), }) .into_inner(); - api::server_wrap( - &state, - &req, - payload, - delete_customer, - api::MerchantAuthentication::ApiKey, - ) - .await + api::server_wrap(&state, &req, payload, delete_customer, &auth::ApiKeyAuth).await } #[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))] @@ -115,7 +105,7 @@ pub async fn get_customer_mandates( |state, merchant_account, req| { crate::core::mandate::get_customer_mandates(state, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index f2ae1aa908d..cdfe8353bcc 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -2,7 +2,11 @@ use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::AppState; -use crate::{core::payments::helpers, services::api, types::api::customers}; +use crate::{ + core::payments::helpers, + services::{api, authentication as auth}, + types::api::customers, +}; #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] pub async fn ephemeral_key_create( @@ -18,7 +22,7 @@ pub async fn ephemeral_key_create( |state, merchant_account, req| { helpers::make_ephemeral_key(state, req.customer_id, merchant_account.merchant_id) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -35,7 +39,7 @@ pub async fn ephemeral_key_delete( &req, payload, |state, _, req| helpers::delete_ephemeral_key(&*state.store, req), - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index ed3ab15ced6..8ae978a0dbe 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -2,7 +2,11 @@ use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -use crate::{core::mandate, services::api, types::api::mandates}; +use crate::{ + core::mandate, + services::{api, authentication as auth}, + types::api::mandates, +}; #[instrument(skip_all, fields(flow = ?Flow::MandatesRetrieve))] // #[get("/{id}")] @@ -19,7 +23,7 @@ pub async fn get_mandate( &req, mandate_id, mandate::get_mandate, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -41,7 +45,7 @@ pub async fn revoke_mandate( |state, merchant_account, req| { mandate::revoke_mandate(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 7d98bac58d6..93da254a9e8 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -4,8 +4,7 @@ use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::payment_methods::cards, - services, - services::api, + services::{api, authentication as auth}, types::api::payment_methods::{self, PaymentMethodId}, }; @@ -23,7 +22,7 @@ pub async fn create_payment_method_api( |state, merchant_account, req| async move { cards::add_payment_method(state, req, &merchant_account).await }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -36,12 +35,12 @@ pub async fn list_payment_method_api( _merchant_id: web::Path<String>, json_payload: web::Query<payment_methods::ListPaymentMethodRequest>, ) -> HttpResponse { - //let merchant_id = merchant_id.into_inner(); - let (payload, auth_type) = - match api::get_auth_type_and_check_client_secret(&req, json_payload.into_inner()) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), - }; + let payload = json_payload.into_inner(); + + let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return api::log_and_return_error_response(e), + }; api::server_wrap( &state, @@ -50,7 +49,7 @@ pub async fn list_payment_method_api( |state, merchant_account, req| { cards::list_payment_methods(&*state.store, merchant_account, req) }, - auth_type, + &*auth, ) .await } @@ -65,11 +64,11 @@ pub async fn list_customer_payment_method_api( ) -> HttpResponse { let customer_id = customer_id.into_inner().0; - let auth_type = - match services::authenticate_eph_key(&req, &*state.store, customer_id.clone()).await { - Ok(auth_type) => auth_type, - Err(err) => return api::log_and_return_error_response(err), - }; + let auth_type = match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await + { + Ok(auth_type) => auth_type, + Err(err) => return api::log_and_return_error_response(err), + }; api::server_wrap( &state, @@ -78,7 +77,7 @@ pub async fn list_customer_payment_method_api( |state, merchant_account, _| { cards::list_customer_payment_method(state, merchant_account, &customer_id) }, - auth_type, + &*auth_type, ) .await } @@ -100,7 +99,7 @@ pub async fn payment_method_retrieve_api( &req, payload, |state, merchant_account, pm| cards::retrieve_payment_method(state, pm, merchant_account), - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -126,7 +125,7 @@ pub async fn payment_method_update_api( &payment_method_id, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -146,7 +145,7 @@ pub async fn payment_method_delete_api( &req, pm, cards::delete_payment_method, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index adee6ff0169..3954c1ea9c0 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1,5 +1,3 @@ -use std::borrow::Cow; - use actix_web::{web, Responder}; use error_stack::report; use router_env::{instrument, tracing, Flow}; @@ -7,7 +5,7 @@ use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{errors::http_not_implemented, payments}, - services::api, + services::{api, authentication as auth}, types::api::{self as api_types, enums as api_enums, payments as payment_types}, }; @@ -37,7 +35,7 @@ pub async fn payments_create( api::AuthFlow::Merchant, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -69,7 +67,7 @@ pub async fn payments_start( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::MerchantId(Cow::Borrowed(&merchant_id)), + &auth::MerchantIdAuth(merchant_id), ) .await } @@ -89,11 +87,10 @@ pub async fn payments_retrieve( param: None, connector: None, }; - let auth_type = match api::get_auth_type(&req) { - Ok(auth_type) => auth_type, + let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; - let _auth_flow = api::get_auth_flow(&auth_type); api::server_wrap( &state, @@ -110,7 +107,7 @@ pub async fn payments_retrieve( payments::CallConnectorAction::Trigger, ) }, - auth_type, + &*auth_type, ) .await } @@ -133,14 +130,11 @@ pub async fn payments_update( payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), + let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), }; - let auth_flow = api::get_auth_flow(&auth_type); - // return http_not_implemented(); api::server_wrap( &state, &req, @@ -154,7 +148,7 @@ pub async fn payments_update( auth_flow, ) }, - auth_type, + &*auth_type, ) .await } @@ -177,13 +171,12 @@ pub async fn payments_confirm( payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); - let auth_type; - (payload, auth_type) = match api::get_auth_type_and_check_client_secret(&req, payload) { - Ok(values) => values, - Err(err) => return api::log_and_return_error_response(err), - }; + let (auth_type, auth_flow) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok(auth) => auth, + Err(e) => return api::log_and_return_error_response(e), + }; - let auth_flow = api::get_auth_flow(&auth_type); api::server_wrap( &state, &req, @@ -197,7 +190,7 @@ pub async fn payments_confirm( auth_flow, ) }, - auth_type, + &*auth_type, ) .await } @@ -230,7 +223,7 @@ pub async fn payments_capture( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -264,7 +257,7 @@ pub async fn payments_connector_session( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::PublishableKey, + &auth::PublishableKeyAuth, ) .await } @@ -296,7 +289,7 @@ pub async fn payments_response( req, ) }, - api::MerchantAuthentication::MerchantId(Cow::Borrowed(&merchant_id)), + &auth::MerchantIdAuth(merchant_id), ) .await } @@ -328,7 +321,7 @@ pub async fn payments_cancel( payments::CallConnectorAction::Trigger, ) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -348,7 +341,7 @@ pub async fn payments_list( |state, merchant_account, req| { payments::list_payments(&*state.store, merchant_account, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index fa325677bc2..35147201320 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -2,7 +2,11 @@ use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -use crate::{core::refunds::*, services::api, types::api::refunds}; +use crate::{ + core::refunds::*, + services::{api, authentication as auth}, + types::api::refunds, +}; /// Refunds - Create /// @@ -28,7 +32,7 @@ pub async fn refunds_create( &req, json_payload.into_inner(), refund_create_core, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -49,7 +53,7 @@ pub async fn refunds_retrieve( |state, merchant_account, refund_id| { refund_response_wrapper(state, merchant_account, refund_id, refund_retrieve_core) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -70,7 +74,7 @@ pub async fn refunds_update( |state, merchant_account, req| { refund_update_core(&*state.store, merchant_account, &refund_id, req) }, - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } @@ -87,7 +91,7 @@ pub async fn refunds_list( &req, payload.into_inner(), |state, merchant_account, req| refund_list(&*state.store, merchant_account, req), - api::MerchantAuthentication::ApiKey, + &auth::ApiKeyAuth, ) .await } diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index 0fd94c44525..078a2870ded 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -2,7 +2,10 @@ use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -use crate::{core::webhooks, services::api}; +use crate::{ + core::webhooks, + services::{api, authentication as auth}, +}; #[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] pub async fn receive_incoming_webhook( @@ -20,7 +23,7 @@ pub async fn receive_incoming_webhook( |state, merchant_account, body| { webhooks::webhooks_core(state, &req, merchant_account, &connector_name, body) }, - api::ConnectorAuthentication::MerchantId(&merchant_id), + &auth::MerchantIdAuth(merchant_id), ) .await } diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 571e3d50a49..fba45c00ba6 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -1,4 +1,5 @@ pub mod api; +pub mod authentication; pub mod encryption; pub mod logger; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index d48bce91684..ce07e4bedb0 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1,7 +1,7 @@ mod client; pub(crate) mod request; -use std::{borrow::Cow, collections::HashMap, fmt::Debug, future::Future, str, time::Instant}; +use std::{collections::HashMap, fmt::Debug, future::Future, str, time::Instant}; use actix_web::{body, HttpRequest, HttpResponse, Responder}; use bytes::Bytes; @@ -15,18 +15,18 @@ pub use self::request::{Method, Request, RequestBuilder}; use crate::{ configs::settings::Connectors, core::{ - errors::{self, CustomResult, RouterResponse, RouterResult, StorageErrorExt}, + errors::{self, CustomResult, RouterResponse, RouterResult}, payments, }, db::StorageInterface, logger, routes::AppState, + services::authentication as auth, types::{ self, api, - storage::{self, enums}, + storage::{self}, ErrorResponse, }, - utils::{self, OptionExt}, }; pub type BoxedConnectorIntegration<'a, T, Req, Resp> = @@ -363,104 +363,49 @@ impl RedirectForm { } } -#[derive(Clone, Debug)] -pub enum ApiAuthentication<'a> { - Merchant(MerchantAuthentication<'a>), - Connector(ConnectorAuthentication<'a>), -} - -#[derive(Clone, Debug)] -pub enum MerchantAuthentication<'a> { - ApiKey, - MerchantId(Cow<'a, str>), - AdminApiKey, - PublishableKey, -} - -#[derive(Clone, Debug)] -pub enum ConnectorAuthentication<'a> { - MerchantId(&'a str), -} - -impl<'a> From<MerchantAuthentication<'a>> for ApiAuthentication<'a> { - fn from(merchant_auth: MerchantAuthentication<'a>) -> Self { - ApiAuthentication::Merchant(merchant_auth) - } -} - -impl<'a> From<ConnectorAuthentication<'a>> for ApiAuthentication<'a> { - fn from(connector_auth: ConnectorAuthentication<'a>) -> Self { - ApiAuthentication::Connector(connector_auth) - } -} - #[derive(Clone, Copy, PartialEq, Eq)] pub enum AuthFlow { Client, Merchant, } -pub fn get_auth_flow(auth_type: &MerchantAuthentication<'_>) -> AuthFlow { - match auth_type { - MerchantAuthentication::ApiKey => AuthFlow::Merchant, - _ => AuthFlow::Client, - } -} - -pub fn get_auth_type(request: &HttpRequest) -> RouterResult<MerchantAuthentication<'_>> { - let api_key = get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; - if api_key.starts_with("pk_") { - Ok(MerchantAuthentication::PublishableKey) - } else { - Ok(MerchantAuthentication::ApiKey) - } -} - -#[instrument(skip(request, payload, state, func))] -pub async fn server_wrap_util<'a, 'b, T, Q, F, Fut>( +#[instrument(skip(request, payload, state, func, api_auth))] +pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut>( state: &'b AppState, request: &'a HttpRequest, payload: T, func: F, - api_authentication: ApiAuthentication<'a>, + api_auth: &dyn auth::AuthenticateAndFetch<U>, ) -> RouterResult<BachResponse<Q>> where - F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut, + F: Fn(&'b AppState, U, T) -> Fut, Fut: Future<Output = RouterResponse<Q>>, Q: Serialize + Debug + 'a, T: Debug, { - let merchant_account = match api_authentication { - ApiAuthentication::Merchant(merchant_auth) => { - authenticate_merchant(request, state, merchant_auth).await? - } - ApiAuthentication::Connector(connector_auth) => { - authenticate_connector(request, &*state.store, connector_auth).await? - } - }; - logger::debug!(request=?payload); - func(state, merchant_account, payload).await + let auth_out = api_auth + .authenticate_and_fetch(request.headers(), state) + .await?; + func(state, auth_out, payload).await } #[instrument( - skip(request, payload, state, func), + skip(request, payload, state, func, api_auth), fields(request_method, request_url_path) )] -pub async fn server_wrap<'a, 'b, A, T, Q, F, Fut>( +pub async fn server_wrap<'a, 'b, T, U, Q, F, Fut>( state: &'b AppState, request: &'a HttpRequest, payload: T, func: F, - api_authentication: A, + api_auth: &dyn auth::AuthenticateAndFetch<U>, ) -> HttpResponse where - A: Into<ApiAuthentication<'a>> + Debug, - F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut, + F: Fn(&'b AppState, U, T) -> Fut, Fut: Future<Output = RouterResult<BachResponse<Q>>>, Q: Serialize + Debug + 'a, T: Debug, { - let api_authentication = api_authentication.into(); let request_method = request.method().as_str(); let url_path = request.path(); tracing::Span::current().record("request_method", request_method); @@ -469,7 +414,7 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest); - let res = match server_wrap_util(state, request, payload, func, api_authentication).await { + let res = match server_wrap_util(state, request, payload, func, api_auth).await { Ok(BachResponse::Json(response)) => match serde_json::to_string(&response) { Ok(res) => http_response_json(res), Err(_) => http_response_err( @@ -519,120 +464,6 @@ where error.current_context().error_response() } -pub async fn authenticate_merchant<'a>( - request: &HttpRequest, - state: &AppState, - merchant_authentication: MerchantAuthentication<'a>, -) -> RouterResult<storage::MerchantAccount> { - match merchant_authentication { - MerchantAuthentication::ApiKey => { - let api_key = - get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; - authenticate_by_api_key(&*state.store, api_key).await - } - - MerchantAuthentication::MerchantId(merchant_id) => (*state.store) - .find_merchant_account_by_merchant_id(&merchant_id) - .await - .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::Unauthorized)), - - MerchantAuthentication::AdminApiKey => { - let admin_api_key = - get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; - utils::when(admin_api_key != state.conf.keys.admin_api_key, || { - Err(errors::ApiErrorResponse::Unauthorized) - .into_report() - .attach_printable("Admin Authentication Failure") - })?; - - Ok(storage::MerchantAccount { - id: -1, - merchant_id: String::from("juspay"), - merchant_name: None, - api_key: None, - merchant_details: None, - return_url: None, - webhook_details: None, - routing_algorithm: None, - custom_routing_rules: None, - sub_merchants_enabled: None, - parent_merchant_id: None, - enable_payment_response_hash: false, - payment_response_hash_key: None, - redirect_to_merchant_with_http_post: false, - publishable_key: None, - storage_scheme: enums::MerchantStorageScheme::PostgresOnly, - locker_id: None, - }) - } - - MerchantAuthentication::PublishableKey => { - let api_key = - get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; - authenticate_by_publishable_key(&*state.store, api_key).await - } - } -} - -pub async fn authenticate_connector<'a>( - _request: &HttpRequest, - store: &dyn StorageInterface, - connector_authentication: ConnectorAuthentication<'a>, -) -> RouterResult<storage::MerchantAccount> { - match connector_authentication { - ConnectorAuthentication::MerchantId(merchant_id) => store - .find_merchant_account_by_merchant_id(merchant_id) - .await - .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::Unauthorized)), - } -} - -pub fn get_auth_type_and_check_client_secret<P>( - req: &HttpRequest, - payload: P, -) -> RouterResult<(P, MerchantAuthentication<'_>)> -where - P: Authenticate, -{ - let auth_type = get_auth_type(req)?; - Ok(( - payments::helpers::client_secret_auth(payload, &auth_type)?, - auth_type, - )) -} - -pub async fn authenticate_eph_key<'a>( - req: &'a HttpRequest, - store: &dyn StorageInterface, - customer_id: String, -) -> RouterResult<MerchantAuthentication<'a>> { - let api_key = get_api_key(req)?; - if api_key.starts_with("epk") { - let ek = store - .get_ephemeral_key(api_key) - .await - .change_context(errors::ApiErrorResponse::Unauthorized)?; - utils::when(ek.customer_id.ne(&customer_id), || { - Err(report!(errors::ApiErrorResponse::InvalidEphermeralKey)) - })?; - Ok(MerchantAuthentication::MerchantId(Cow::Owned( - ek.merchant_id, - ))) - } else { - Ok(MerchantAuthentication::ApiKey) - } -} - -fn get_api_key(req: &HttpRequest) -> RouterResult<&str> { - req.headers() - .get("api-key") - .get_required_value("api-key")? - .to_str() - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to convert API key to string") -} - pub async fn authenticate_by_api_key( store: &dyn StorageInterface, api_key: &str, @@ -644,17 +475,6 @@ pub async fn authenticate_by_api_key( .attach_printable("Merchant not authenticated") } -async fn authenticate_by_publishable_key( - store: &dyn StorageInterface, - publishable_key: &str, -) -> RouterResult<storage::MerchantAccount> { - store - .find_merchant_account_by_publishable_key(publishable_key) - .await - .change_context(errors::ApiErrorResponse::Unauthorized) - .attach_printable("Merchant not authenticated") -} - pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { HttpResponse::Ok() .content_type("application/json") diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs new file mode 100644 index 00000000000..01218d28cb2 --- /dev/null +++ b/crates/router/src/services/authentication.rs @@ -0,0 +1,194 @@ +use actix_web::http::header::HeaderMap; +use api_models::{payment_methods::ListPaymentMethodRequest, payments::PaymentsRequest}; +use async_trait::async_trait; +use error_stack::{report, IntoReport, ResultExt}; + +use crate::{ + core::errors::{self, RouterResult, StorageErrorExt}, + db::StorageInterface, + routes::AppState, + services::api, + types::storage, + utils::OptionExt, +}; + +#[async_trait] +pub trait AuthenticateAndFetch<T> { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<T>; +} + +#[derive(Debug)] +pub struct ApiKeyAuth; + +#[async_trait] +impl AuthenticateAndFetch<storage::MerchantAccount> for ApiKeyAuth { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<storage::MerchantAccount> { + let api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + state + .store + .find_merchant_account_by_api_key(api_key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Merchant not authenticated") + } +} + +#[derive(Debug)] +pub struct AdminApiAuth; + +#[async_trait] +impl AuthenticateAndFetch<()> for AdminApiAuth { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<()> { + let admin_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + if admin_api_key != state.conf.keys.admin_api_key { + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure"))?; + } + Ok(()) + } +} + +#[derive(Debug)] +pub struct MerchantIdAuth(pub String); + +#[async_trait] +impl AuthenticateAndFetch<storage::MerchantAccount> for MerchantIdAuth { + async fn authenticate_and_fetch( + &self, + _request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<storage::MerchantAccount> { + state + .store + .find_merchant_account_by_merchant_id(self.0.as_ref()) + .await + .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::Unauthorized)) + } +} + +#[derive(Debug)] +pub struct PublishableKeyAuth; + +#[async_trait] +impl AuthenticateAndFetch<storage::MerchantAccount> for PublishableKeyAuth { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<storage::MerchantAccount> { + let publishable_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + state + .store + .find_merchant_account_by_publishable_key(publishable_key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Merchant not authenticated") + } +} + +pub trait ClientSecretFetch { + fn get_client_secret(&self) -> Option<&String>; +} + +impl ClientSecretFetch for PaymentsRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + +impl ClientSecretFetch for ListPaymentMethodRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + +pub fn get_auth_type_and_flow( + headers: &HeaderMap, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<storage::MerchantAccount>>, + api::AuthFlow, +)> { + let api_key = get_api_key(headers)?; + + if api_key.starts_with("pk_") { + return Ok((Box::new(PublishableKeyAuth), api::AuthFlow::Client)); + } + Ok((Box::new(PublishableKeyAuth), api::AuthFlow::Merchant)) +} + +pub fn check_client_secret_and_get_auth( + headers: &HeaderMap, + payload: &impl ClientSecretFetch, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<storage::MerchantAccount>>, + api::AuthFlow, +)> { + let api_key = get_api_key(headers)?; + + if api_key.starts_with("pk_") { + payload + .get_client_secret() + .check_value_present("client_secret") + .map_err(|_| errors::ApiErrorResponse::MissingRequiredField { + field_name: "client_secret".to_owned(), + })?; + return Ok((Box::new(PublishableKeyAuth), api::AuthFlow::Client)); + } + + if payload.get_client_secret().is_some() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "client_secret is not a valid parameter".to_owned(), + } + .into()); + } + + Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant)) +} + +pub async fn is_ephemeral_auth( + headers: &HeaderMap, + db: &dyn StorageInterface, + customer_id: &str, +) -> RouterResult<Box<dyn AuthenticateAndFetch<storage::MerchantAccount>>> { + let api_key = get_api_key(headers)?; + + if !api_key.starts_with("epk") { + return Ok(Box::new(ApiKeyAuth)); + } + + let ephemeral_key = db + .get_ephemeral_key(api_key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + if ephemeral_key.customer_id.ne(customer_id) { + return Err(report!(errors::ApiErrorResponse::InvalidEphermeralKey)); + } + + Ok(Box::new(MerchantIdAuth(ephemeral_key.merchant_id))) +} + +fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> { + headers + .get("api-key") + .get_required_value("api-key")? + .to_str() + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert API key to string") +}
refactor
Refactored Authentication (#327)
8eca66a2eb8770783c671b299765aa15d7fa72f8
2023-10-29 20:15:27
github-actions
test(postman): update postman collection files
false
diff --git a/postman/collection-json/forte.postman_collection.json b/postman/collection-json/forte.postman_collection.json index cdf381f9f2d..8297b4778f4 100644 --- a/postman/collection-json/forte.postman_collection.json +++ b/postman/collection-json/forte.postman_collection.json @@ -523,7 +523,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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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,\"routing\":{\"type\":\"single\",\"data\":\"forte\"},\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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", @@ -646,6 +646,248 @@ { "name": "Happy Cases", "item": [ + { + "name": "Scenario7-Create payment with Zero Amount", + "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.\",", + " );", + "}", + "", + "// Response body should have value \"processing\" 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\":0,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"routing\":{\"type\":\"single\",\"data\":\"forte\"},\"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\":\"Fix\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\",\"last_name\":\"Fix\"}},\"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 \"processing\" 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\");", + " },", + " );", + "}", + "" + ], + "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": "Scenario1-Create payment with confirm true", "item": [
test
update postman collection files
56d12ce5eb92421be97c593021aca382ca321f35
2023-05-08 16:29:43
Sampras Lopes
ci(migrations): add diesel migrations validations (#1056)
false
diff --git a/.github/workflows/migration-check.yaml b/.github/workflows/migration-check.yaml new file mode 100644 index 00000000000..b913949d6c8 --- /dev/null +++ b/.github/workflows/migration-check.yaml @@ -0,0 +1,66 @@ +name: Migration Consistency Tests + +on: + pull_request: + + merge_group: + types: + - checks_requested + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # Allow more retries for network requests in cargo (downloading crates) and + # rustup (installing toolchains). This should help to reduce flaky CI failures + # from transient network timeouts or other issues. + CARGO_NET_RETRY: 10 + RUSTUP_MAX_RETRIES: 10 + # Use cargo's sparse index protocol + CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse + +jobs: + migration_verify: + name: Verify consistency of migrations with `schema.rs` file + runs-on: ubuntu-latest + + services: + postgres: + image: postgres + env: + POSTGRES_PASSWORD: postgres + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432:5432 + + steps: + - name: Checkout repository + uses: actions/[email protected] + + - name: Install Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + + - uses: Swatinem/[email protected] + + - name: Install diesel_cli + shell: bash + run: cargo install diesel_cli --no-default-features --features postgres + + - name: Verify `diesel migration run` + shell: bash + env: + DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres + run: diesel migration run --locked-schema + + - name: Verify `diesel migration redo` + shell: bash + env: + DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres + run: diesel migration redo -a --locked-schema diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs index f92f742d71c..c34f67705d5 100644 --- a/crates/storage_models/src/merchant_account.rs +++ b/crates/storage_models/src/merchant_account.rs @@ -35,9 +35,9 @@ pub struct MerchantAccount { pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub api_key: Option<StrongSecret<String>>, + pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, - pub intent_fulfillment_time: Option<i64>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index ebe21291567..3f50d837322 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -247,9 +247,9 @@ diesel::table! { routing_algorithm -> Nullable<Json>, primary_business_details -> Json, api_key -> Nullable<Varchar>, + intent_fulfillment_time -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, - intent_fulfillment_time -> Nullable<Int8>, } } diff --git a/migrations/2023-01-20-113235_add_attempt_id_to_payment_intent/down.sql b/migrations/2023-01-20-113235_add_attempt_id_to_payment_intent/down.sql index dd47bba7b53..f6777dd65aa 100644 --- a/migrations/2023-01-20-113235_add_attempt_id_to_payment_intent/down.sql +++ b/migrations/2023-01-20-113235_add_attempt_id_to_payment_intent/down.sql @@ -2,4 +2,4 @@ DROP INDEX payment_attempt_payment_id_merchant_id_index; CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_index ON payment_attempt (payment_id, merchant_id); DROP INDEX payment_attempt_payment_id_merchant_id_attempt_id_index; -ALTER TABLE PAYMENT_INTENT DROP COLUMN attempt_id; \ No newline at end of file +ALTER TABLE PAYMENT_INTENT DROP COLUMN active_attempt_id; diff --git a/migrations/2023-02-28-072631_ang-currency/down.sql b/migrations/2023-02-28-072631_ang-currency/down.sql index e69de29bb2d..e0ac49d1ecf 100644 --- a/migrations/2023-02-28-072631_ang-currency/down.sql +++ b/migrations/2023-02-28-072631_ang-currency/down.sql @@ -0,0 +1 @@ +SELECT 1; diff --git a/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql b/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql index e69de29bb2d..e0ac49d1ecf 100644 --- a/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql +++ b/migrations/2023-02-28-112730_add_refund_webhook_types/down.sql @@ -0,0 +1 @@ +SELECT 1;
ci
add diesel migrations validations (#1056)
3eff4ebd3a60b5831cbec0158527475c8f7d7eb4
2024-03-12 19:40:29
Swangi Kumari
refactor(connector): [Checkout] remove Paypal from wasm (#4044)
false
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 9868346d49e..58e54c36220 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -743,8 +743,6 @@ merchant_secret="Source verification key" payment_method_type = "apple_pay" [[checkout.wallet]] payment_method_type = "google_pay" -[[checkout.wallet]] - payment_method_type = "paypal" [checkout.connector_auth.SignatureKey] api_key="Checkout API Public Key" key1="Processing Channel ID" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 8921ca3bd36..c93acee4736 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -743,8 +743,6 @@ merchant_secret="Source verification key" payment_method_type = "apple_pay" [[checkout.wallet]] payment_method_type = "google_pay" -[[checkout.wallet]] - payment_method_type = "paypal" [checkout.connector_auth.SignatureKey] api_key="Checkout API Public Key" key1="Processing Channel ID"
refactor
[Checkout] remove Paypal from wasm (#4044)
0b404c317e5072c6f02858de547ba02c79cad0bf
2022-12-20 18:30:48
Kartikeya Hegde
fix: Cancellation reason null in payments_retrieve (#184)
false
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 801b0b0c4c7..5118ceab553 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -370,6 +370,7 @@ where mandate_id, shipping: address.shipping, billing: address.billing, + cancellation_reason: payment_attempt.cancellation_reason, ..Default::default() }), })
fix
Cancellation reason null in payments_retrieve (#184)
0c8f8f5f5ce12000725a5105824b7d3375a1ac29
2025-03-05 18:23:01
github-actions
chore(version): 2025.03.05.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b6ffaf6f55..ba28dcd6867 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ All notable changes to HyperSwitch will be documented here. +- - - + +## 2025.03.05.1 + +### Features + +- **connector:** + - Add template code for recurly ([#7284](https://github.com/juspay/hyperswitch/pull/7284)) ([`a1691d1`](https://github.com/juspay/hyperswitch/commit/a1691d1b85226f336514d2c0dd4707cda131c69b)) + - [Moneris] Implement mandate for Moneris ([#7322](https://github.com/juspay/hyperswitch/pull/7322)) ([`ba84b00`](https://github.com/juspay/hyperswitch/commit/ba84b00edebb5884fb68270ad8cf3e3f50883c55)) +- **router:** Add proxy-confirm-intent api for payments in v2 flow ([#7215](https://github.com/juspay/hyperswitch/pull/7215)) ([`30f321b`](https://github.com/juspay/hyperswitch/commit/30f321bc2001264f5197172428ecae79896ad2f5)) + +### Bug Fixes + +- **connector:** [Braintree] Consume merchant_account_id and merchant_config_currency in payment requests ([#7408](https://github.com/juspay/hyperswitch/pull/7408)) ([`00d69bd`](https://github.com/juspay/hyperswitch/commit/00d69bd924c1c8368ea6ab1af32a2f258c1a94c1)) + +### Miscellaneous Tasks + +- Address Rust 1.85.0 clippy lints ([#7376](https://github.com/juspay/hyperswitch/pull/7376)) ([`38bb767`](https://github.com/juspay/hyperswitch/commit/38bb7676be4015ee6e256110f564b7d573f89c91)) + +**Full Changelog:** [`2025.03.05.0...2025.03.05.1`](https://github.com/juspay/hyperswitch/compare/2025.03.05.0...2025.03.05.1) + + - - - ## 2025.03.05.0
chore
2025.03.05.1
da1f23d2353c19f43f23f0938c1c73e109edc0c5
2024-09-30 20:06:29
Apoorv Dixit
fix(payments_list): remove time range to filter payments attempts (#6159)
false
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index e07d716fb6c..ad056aef6d0 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -369,7 +369,6 @@ impl PaymentAttempt { payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ) -> StorageResult<i64> { @@ -379,14 +378,6 @@ impl PaymentAttempt { .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); - if let Some(time_range) = time_range { - filter = filter.filter(dsl::created_at.ge(time_range.start_time)); - - if let Some(end_time) = time_range.end_time { - filter = filter.filter(dsl::created_at.le(end_time)); - } - } - if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 5f0894566ad..c71e08c79e8 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -157,7 +157,6 @@ pub trait PaymentAttemptInterface { payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, errors::StorageError>; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d00d4b7b259..6e785b55a3f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3243,7 +3243,6 @@ pub async fn apply_filters_on_payments( constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, - constraints.time_range, pi_fetch_constraints.get_profile_id_list(), merchant.storage_scheme, ) diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 73d05528634..de10b70f507 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1604,7 +1604,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::DataStorageError> { @@ -1617,7 +1616,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type, authentication_type, merchant_connector_id, - time_range, profile_id_list, storage_scheme, ) diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 44c089932d9..c37f9f6d3da 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -52,7 +52,6 @@ impl PaymentAttemptInterface for MockDb { _payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - _time_range: Option<common_utils::types::TimeRange>, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 6d669437efd..63f5a0ff9f8 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -403,7 +403,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -427,7 +426,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method, payment_method_type, authentication_type, - time_range, profile_id_list, merchant_connector_id, ) @@ -1289,7 +1287,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -1302,7 +1299,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, - time_range, profile_id_list, storage_scheme, )
fix
remove time range to filter payments attempts (#6159)
5e7e0d829a7deeed6b50af9633f6d2307b51c4bd
2025-02-25 12:20:30
Sakil Mostak
fix(core): make parsing optional for connector_wallet_details in session token flow (#7365)
false
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 662453c4a3e..54035900846 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -930,7 +930,7 @@ fn create_gpay_session_token( ) -> RouterResult<types::PaymentsSessionRouterData> { // connector_wallet_details is being parse into admin types to check specifically if google_pay field is present // this is being done because apple_pay details from metadata is also being filled into connector_wallets_details - let connector_wallets_details = router_data + let google_pay_wallets_details = router_data .connector_wallets_details .clone() .parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails") @@ -939,10 +939,14 @@ fn create_gpay_session_token( "cannot parse connector_wallets_details from the given value {:?}", router_data.connector_wallets_details )) - .change_context(errors::ApiErrorResponse::InvalidDataFormat { - field_name: "connector_wallets_details".to_string(), - expected_format: "admin_types_connector_wallets_details_format".to_string(), - })?; + .map_err(|err| { + logger::debug!( + "Failed to parse connector_wallets_details for google_pay flow: {:?}", + err + ); + }) + .ok() + .and_then(|connector_wallets_details| connector_wallets_details.google_pay); let connector_metadata = router_data.connector_meta_data.clone(); let delayed_response = is_session_response_delayed(state, connector); @@ -996,7 +1000,7 @@ fn create_gpay_session_token( enums::PaymentMethodType::GooglePay, ); - if connector_wallets_details.google_pay.is_some() { + if google_pay_wallets_details.is_some() { let gpay_data = router_data .connector_wallets_details .clone()
fix
make parsing optional for connector_wallet_details in session token flow (#7365)
a083f700ff95a0d9fddf716e298454fc6750dd49
2022-11-23 19:08:43
Sanchith Hegde
docs(CONTRIBUTING): update contributing guidelines based on Tokio (#9)
false
diff --git a/contrib/CONTRIBUTING.md b/contrib/CONTRIBUTING.md index 30f051d3d8a..26f97aadbdc 100644 --- a/contrib/CONTRIBUTING.md +++ b/contrib/CONTRIBUTING.md @@ -1,22 +1,548 @@ -# Want to contribute? +# Contributing to Orca -## Before you contribute +:tada: First off, thanks for taking the time to contribute! +We are so happy to have you! :tada: -Before you start working on a larger contribution, you should get in touch with us first through the issue tracker with your idea so that we can help out and possibly guide you. Coordinating up front makes it much easier. +There are opportunities to contribute to Orca at any level. +It doesn't matter if you are just getting started with Rust or are the most +weathered expert, we can use your help. -There are multiple ways to contribute to this product -* Adding a new connector.[Refer here for instuctions](/add_connector.md) -* Improving the readability of the code. *The aim for this project is to make sure even non-rust programmers understand the payment journey. Hence, some of the code in core functions (e.g. payments_core) is written to be more readable rather than being idiomatic.* -* Bug fixes and feature enhancements +**No contribution is too small and all contributions are valued.** -## Getting familiar with the project +This guide will help you get started. +**Do not let this guide intimidate you.** +It should be considered a map to help you navigate the process. -The architecture is somewhat unique; it was originally inspired by XML pull parsers, but ended up going in somewhat of its own direction. To get familiar with it, +You can also get help with contributing on our [Discussions][discussions] space. +Please join us! - start by reading the README page, which gives some details on the product and its goals +[discussions]: https://github.com/juspay/orca/discussions -The source code can be approached by skimming the API documentation first (we have an open_api.yaml file which could be viewed as documentation using any open API editor or plugins), then explore the code. +## Table of Contents -## Code reviews +- [Code of Conduct](#code-of-conduct) +- [Contributing in Issues](#contributing-in-issues) + - [Asking for General Help](#asking-for-general-help) + - [Submitting a Bug Report](#submitting-a-bug-report) + - [Triaging a Bug Report](#triaging-a-bug-report) + - [Resolving a Bug Report](#resolving-a-bug-report) +- [Pull Requests](#pull-requests) + - [Cargo Commands](#cargo-commands) + - [Commits](#commits) + - [Opening the Pull Request](#opening-the-pull-request) + - [Discuss and update](#discuss-and-update) + - [Commit Squashing](#commit-squashing) +- [Reviewing Pull Requests](#reviewing-pull-requests) + - [Review a bit at a time](#review-a-bit-at-a-time) + - [Be aware of the person behind the code](#be-aware-of-the-person-behind-the-code) + - [Abandoned or Stalled Pull Requests](#abandoned-or-stalled-pull-requests) +- [Keeping track of issues and PRs](#keeping-track-of-issues-and-prs) + - [Area](#area) + - [Category](#category) + - [Calls for participation](#calls-for-participation) + - [Metadata](#metadata) + - [Priority](#priority) + - [Status](#status) -All submissions, including submissions by project members, requires detailed review before getting merged. We use GitHub pull requests for this purpose. \ No newline at end of file +## Code of Conduct + +The Orca project adheres to the [Rust Code of Conduct][coc]. +This describes the _minimum_ behavior expected from all contributors. + +[coc]: https://www.rust-lang.org/policies/code-of-conduct + +## Contributing in Issues + +For any issue, there are fundamentally three ways an individual can contribute: + +1. By opening the issue for discussion: For instance, if you believe that you + have discovered a bug in Orca, creating a new issue in [the juspay/orca issue + tracker][issue] is the way to report it. + +2. By helping to triage the issue: This can be done by providing supporting + details (a test case that demonstrates a bug), providing suggestions on how + to address the issue, or ensuring that the issue is tagged correctly. + +3. By helping to resolve the issue: Typically this is done either in the form of + demonstrating that the issue reported is not a problem after all, or more + often, by opening a Pull Request that changes some bit of something in Orca + in a concrete and reviewable manner. + +[issue]: https://github.com/juspay/orca/issues + +**Anybody can participate in any stage of contribution**. +We urge you to participate in the discussion around bugs and participate in +reviewing PRs. + +### Asking for General Help + +If you have reviewed existing documentation and still have questions or are +having problems, you can [open a discussion] asking for help. + +In exchange for receiving help, we ask that you contribute back a documentation +PR that helps others avoid the problems that you encountered. + +[open a discussion]: https://github.com/juspay/orca/discussions/new + +### Submitting a Bug Report + +When opening a new issue in the Orca issue tracker, you will be presented with a +basic template that should be filled in. +If you believe that you have uncovered a bug, please fill out this form, +following the template to the best of your ability. +Do not worry if you cannot answer every detail, just fill in what you can. + +The two most important pieces of information we need in order to properly +evaluate the report is a description of the behavior you are seeing and a simple +test case we can use to recreate the problem on our own. +If we cannot recreate the issue, it becomes impossible for us to fix. + +See [How to create a Minimal, Complete, and Verifiable example][mcve]. + +[mcve]: https://stackoverflow.com/help/mcve + +### Triaging a Bug Report + +Once an issue has been opened, it is not uncommon for there to be discussion +around it. +Some contributors may have differing opinions about the issue, including whether +the behavior being seen is a bug or a feature. +This discussion is part of the process and should be kept focused, helpful, and +professional. + +Short, clipped responses — that provide neither additional context nor +supporting detail — are not helpful or professional. +To many, such responses are simply annoying and unfriendly. + +Contributors are encouraged to help one another make forward progress as much as +possible, empowering one another to solve issues collaboratively. +If you choose to comment on an issue that you feel either is not a problem that +needs to be fixed, or if you encounter information in an issue that you feel is +incorrect, explain why you feel that way with additional supporting context, and +be willing to be convinced that you may be wrong. +By doing so, we can often reach the correct outcome much faster. + +### Resolving a Bug Report + +In the majority of cases, issues are resolved by opening a Pull Request. +The process for opening and reviewing a Pull Request is similar to that of +opening and triaging issues, but carries with it a necessary review and approval +workflow that ensures that the proposed changes meet the minimal quality and +functional guidelines of the Orca project. + +## Pull Requests + +Pull Requests are the way concrete changes are made to the code, documentation, +and dependencies in the Orca repository. + +Even tiny pull requests (e.g., one character pull request fixing a typo in API +documentation) are greatly appreciated. +Before making a large change, it is usually a good idea to first open an issue +describing the change to solicit feedback and guidance. +This will increase the likelihood of the PR getting merged. + +### Cargo Commands + +Due to the extensive use of features in Orca, you will often need to add extra +arguments to many common cargo commands. +This section lists some commonly needed commands. + +Some commands just need the `--all-features` argument: + +```shell +cargo check --all-features +cargo clippy --all-features +cargo test --all-features +``` + +The `cargo fmt` command requires the nightly toolchain, as we use a few of the +unstable features: + +```shell +cargo +nightly fmt +``` + +### Commits + +It is a recommended best practice to keep your changes as logically grouped as +possible within individual commits. +There is no limit to the number of commits any single Pull Request may have, and +many contributors find it easier to review changes that are split across +multiple commits. + +That said, if you have a number of commits that are "checkpoints" and don't +represent a single logical change, please squash those together. + +Note that multiple commits often get squashed when they are landed (see the +notes about [commit squashing](#commit-squashing)). + +#### Commit message guidelines + +Each commit message consists of a header, an optional body, and an optional +footer. + +```text +<header> +<BLANK LINE> +<optional body> +<BLANK LINE> +<optional footer> +``` + +The `header` is mandatory and must conform to the +[commit message header](#commit-message-header) format. + +The `body` is optional. +When the body is present it must be at least 20 characters long and must conform +to the [commit message body](#commit-message-body) format. + +The `footer` is optional. +The [commit message footer](#commit-message-footer) format describes what the +footer is used for and the structure it must have. + +##### Commit message header + +```text +<type>(<scope>): <short summary> +│ │ │ +│ │ └── Summary in present tense. +| | Not capitalized. +| | No period at the end. +│ │ +│ └── Commit Scope: crate name | changelog | config | migrations +| | openapi | postman +│ +└── Commit Type: build | chore | ci | docs | feat | fix | perf | refactor | test +``` + +The `<type>` and `<summary>` fields are mandatory, the (`<scope>`) field is +optional. + +`<type>` must be one of the following: + +- `build`: Changes that affect the build system or external dependencies + (example scopes: `deps`, `dev-deps`, `metadata`) +- `chore`: Changes such as fixing formatting or addressing warnings or lints, or + other maintenance changes +- `ci`: Changes to our CI configuration files and scripts (examples: `workflows`, + `dependabot`, `renovate`) +- `docs`: Documentation only changes +- `feat`: A new feature +- `fix`: A bug fix +- `perf`: A code change that improves performance +- `refactor`: A code change that neither fixes a bug nor adds a feature +- `test`: Adding missing tests or correcting existing tests + +`<scope>` should be the name of the crate affected (as perceived by the person +reading the changelog generated from commit messages). +The scope can be more specific if the changes are targeted towards the main +crate in the repository (`router`). + +The following is the list of supported scopes: + +- `masking` +- `router` +- `router_derive` +- `router_env` + +There are currently a few exceptions to the "use crate name" rule: + +- `changelog`: Used for updating the release notes in the `CHANGELOG.md` file. + Commonly used with the `docs` commit type + (e.g. `docs(changelog): generate release notes for v0.4.0 release`). +- `config`: Used for changes which affect the configuration files of any of the + services. +- `migrations`: Used for changes to the database migration scripts. +- `openapi`: Used for changes to the OpenAPI specification file. +- `postman`: Used for changes to the Postman collection file. +- none/empty string: Useful for test and refactor changes that are done across + all crates (e.g. `test: add missing unit tests`) and for docs changes that are + not related to a specific crate (e.g. `docs: fix typo in tutorial`). + +Use the `<summary>` field to provide a succinct description of the change: + +- Use the imperative, present tense: "change" not "changed" nor "changes". +- Don't capitalize the first letter. +- No period (.) at the end. + +##### Commit message body + +Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor +"fixes". + +Explain the motivation for the change in the commit message body. +This commit message should explain why you are making the change. +You can include a comparison of the previous behavior with the new behavior in +order to illustrate the impact of the change. + +##### Commit message footer + +The footer can contain information about breaking changes and deprecations and +is also the place to reference GitHub issues, Jira tickets, and other PRs that +this commit closes or is related to. +For example: + +```text +BREAKING CHANGE: <breaking change summary> +<BLANK LINE> +<breaking change description + migration instructions> +<BLANK LINE> +<BLANK LINE> +Fixes #<issue number> +``` + +or + +```text +DEPRECATED: <what is deprecated> +<BLANK LINE> +<deprecation description + recommended update path> +<BLANK LINE> +<BLANK LINE> +Closes #<PR number> +``` + +Breaking Change section should start with the phrase "BREAKING CHANGE: " +followed by a summary of the breaking change, a blank line, and a detailed +description of the breaking change that also includes migration instructions. + +Similarly, a Deprecation section should start with "DEPRECATED: " followed by a +short description of what is deprecated, a blank line, and a detailed +description of the deprecation that also mentions the recommended update path. + +If the commit reverts a previous commit, it should begin with `revert:`, +followed by the header of the reverted commit. +The content of the commit message body should contain: + +- Information about the SHA of the commit being reverted in the following + format: `This reverts commit <SHA>`. +- A clear description of the reason for reverting the commit message. + +Sample commit messages: + +1. ```text + feat(router): add 3ds support to payments core flow + + + Implement Redirection flow support. This can be used by any flow that + requires redirection. + + Fixes ORCA-123 + ``` + +2. ```text + chore: run formatter + ``` + +3. ```text + fix(config): fix binary name displayed in help message + ``` + +_Adapted from the [Angular Commit Message convention][angular commit message]._ + +[angular commit message]: https://github.com/angular/angular/blob/d684148f93837cf0e4e37146a8df17dc70403558/CONTRIBUTING.md#-commit-message-format + +### Opening the Pull Request + +From within GitHub, opening a new Pull Request will present you with a +[template] that should be filled out. Please try to do your best at filling out +the details, but feel free to skip parts if you're not sure what to put. + +[template]: /.github/PULL_REQUEST_TEMPLATE.md + +### Discuss and update + +You will probably get feedback or requests for changes to your Pull Request. +This is a big part of the submission process so don't be discouraged! +Some contributors may sign off on the Pull Request right away, others may have +more detailed comments or feedback. +This is a necessary part of the process in order to evaluate whether the changes +are correct and necessary. + +**Any community member can review a PR and you might get conflicting feedback**. +Keep an eye out for comments from code owners to provide guidance on conflicting +feedback. + +**Once the PR is open, do not rebase the commits**. +See [Commit Squashing](#commit-squashing) for more details. + +### Commit Squashing + +In most cases, **do not squash commits that you add to your Pull Request during +the review process**. +When the commits in your Pull Request land, they may be squashed into one commit +per logical change. +Metadata will be added to the commit message (including links to the Pull +Request, links to relevant issues, and the names of the reviewers). +The commit history of your Pull Request, however, will stay intact on the Pull +Request page. + +## Reviewing Pull Requests + +**Any Orca community member is welcome to review any pull request**. + +All Orca contributors who choose to review and provide feedback on Pull Requests +have a responsibility to both the project and the individual making the +contribution. +Reviews and feedback must be helpful, insightful, and geared towards improving +the contribution as opposed to simply blocking it. +If there are reasons why you feel the PR should not land, explain what those are. +Do not expect to be able to block a Pull Request from advancing simply because +you say "No" without giving an explanation. +Be open to having your mind changed. +Be open to working with the contributor to make the Pull Request better. + +Reviews that are dismissive or disrespectful of the contributor or any other +reviewers are strictly counter to the Code of Conduct. + +When reviewing a Pull Request, the primary goals are for the codebase to improve +and for the person submitting the request to succeed. +**Even if a Pull Request does not land, the submitters should come away from the +experience feeling like their effort was not wasted or unappreciated**. +Every Pull Request from a new contributor is an opportunity to grow the +community. + +### Review a bit at a time + +Do not overwhelm new contributors. + +It is tempting to micro-optimize and make everything about relative performance, +perfect grammar, or exact style matches. +Do not succumb to that temptation. + +Focus first on the most significant aspects of the change: + +1. Does this change make sense for Orca? +2. Does this change make Orca better, even if only incrementally? +3. Are there clear bugs or larger scale issues that need attending to? +4. Is the commit message readable and correct? + If it contains a breaking change is it clear enough? + +Note that only **incremental** improvement is needed to land a PR. +This means that the PR does not need to be perfect, only better than the status +quo. +Follow up PRs may be opened to continue iterating. + +When changes are necessary, _request_ them, do not _demand_ them, and **do not +assume that the submitter already knows how to add a test or run a benchmark**. + +Specific performance optimization techniques, coding styles and conventions +change over time. +The first impression you give to a new contributor never does. + +Nits (requests for small changes that are not essential) are fine, but try to +avoid stalling the Pull Request. +Most nits can typically be fixed by the Orca Collaborator landing the Pull +Request but they can also be an opportunity for the contributor to learn a bit +more about the project. + +It is always good to clearly indicate nits when you comment: e.g. +`Nit: change foo() to bar(). But this is not blocking.` + +If your comments were addressed but were not folded automatically after new +commits or if they proved to be mistaken, please, [hide them][hiding-a-comment] +with the appropriate reason to keep the conversation flow concise and relevant. + +### Be aware of the person behind the code + +Be aware that _how_ you communicate requests and reviews in your feedback can +have a significant impact on the success of the Pull Request. +Yes, we may land a particular change that makes Orca better, but the individual +might just not want to have anything to do with Orca ever again. +The goal is not just having good code. + +### Abandoned or Stalled Pull Requests + +If a Pull Request appears to be abandoned or stalled, it is polite to first +check with the contributor to see if they intend to continue the work before +checking if they would mind if you took it over (especially if it just has nits +left). +When doing so, it is courteous to give the original contributor credit for the +work they started (either by preserving their name and email address in the +commit log, or by using an `Author:` meta-data tag in the commit. + +_Adapted from the [Node.js contributing guide][node]_. + +[node]: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md +[hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment + +## Keeping track of issues and PRs + +The Orca GitHub repository has a lot of issues and PRs to keep track of. +This section explains the meaning of various labels, as well as our [GitHub +project][project]. +The section is primarily targeted at maintainers. +Most contributors aren't able to set these labels. + +### Area + +The area label describes the area relevant to this issue or PR. + +- **A-CI-CD**: This issue/PR concerns our CI/CD setup. +- **A-connector-compatibility**: This issue/PR concerns connector compatibility + code. +- **A-connector-integration**: This issue/PR concerns connector integrations. +- **A-core**: This issue/PR concerns the core flows. +- **A-dependencies**: The issue/PR concerns one or more of our dependencies. +- **A-framework**: The issue/PR concerns code to interact with other systems or + services such as database, Redis, connector APIs, etc. +- **A-infra**: This issue/PR concerns deployments, Dockerfiles, Docker Compose + files, etc. +- **A-process-tracker**: This issue/PR concerns the process tracker code. + +### Category + +- **C-bug**: This issue is a bug report or this PR is a bug fix. +- **C-doc**: This issue/PR concerns changes to the documentation. +- **C-feature**: This issue is a feature request or this PR adds new features. +- **C-tracking-issue**: This is a tracking issue for a proposal or for a + category of bugs. + +### Calls for participation + +- **E-easy**: This is easy, ranging from quick documentation fixes to stuff you + can do after getting a basic idea about our product. +- **E-medium**: This is not `E-easy` or `E-hard`. +- **E-hard**: This either involves very tricky code, is something we don't know + how to solve, or is difficult for some other reason. + +### Metadata + +The metadata label describes additional metadata that are important for sandbox +or production deployments of our application. + +- **M-configuration-changes**: This PR involves configuration changes. +- **M-database-changes**: This PR involves database schema changes. + +### Priority + +- **P-low**: This is a low priority issue. +- **P-medium**: This is not `P-low` or `P-high`. +- **P-high**: This is a high priority issue and must be addressed quickly. + +### Status + +The status label provides information about the status of the issue or PR. + +- **S-awaiting-triage**: This issue or PR is relatively new and has not been + addressed yet. +- **S-blocked**: This issue or PR is blocked on something else, or other + implementation work. +- **S-design**: This issue or PR involves a problem without an obvious solution; + or the proposed solution raises other questions. +- **S-in-progress**: The implementation relevant to this issue/PR is underway. +- **S-invalid**: This is an invalid issue. +- **S-needs-reproduction-steps**: This behavior hasn't been reproduced by the + team. +- **S-unactionable**: There is not enough information to act on this problem. +- **S-unassigned**: This issue has no one assigned to address it. +- **S-waiting-on-author**: This PR is incomplete or the author needs to address + review comments. +- **S-waiting-on-reporter**: Awaiting response from the issue author. +- **S-waiting-on-review**: This PR has been implemented and needs to be reviewed. +- **S-wont-fix**: The proposal in this issue was rejected and will not be + implemented. + +Any label not listed here is not in active use. + +[project]: https://github.com/orgs/juspay/projects/3
docs
update contributing guidelines based on Tokio (#9)
c5003aaa74d8c70cbb696593e57fa59da2212017
2023-09-04 17:44:29
Pa1NarK
ci(postman): Fix Stripe collection to address check failure (#2078)
false
diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index 6a8afebff74..9fc3bc26fc1 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -69,7 +69,7 @@ mod storage { { Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { Err(errors::StorageError::DuplicateValue { - entity: "ephimeral key", + entity: "ephemeral key", key: None, } .into()) diff --git a/postman/collection-dir/stripe/.info.json b/postman/collection-dir/stripe/.info.json index 9f120bd3298..9e761d83cb0 100644 --- a/postman/collection-dir/stripe/.info.json +++ b/postman/collection-dir/stripe/.info.json @@ -1,6 +1,6 @@ { "info": { - "_postman_id": "a64a0a71-3270-4f9a-828b-e65f9704739c", + "_postman_id": "b4f11b9e-244e-4f34-b5dd-418dcdc91699", "name": "stripe", "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", 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 e958012fc3b..21f05484389 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 @@ -78,6 +78,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Partial refund/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Partial refund/Payments - Create/request.json index 0d6523e82ba..b5f464abc14 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Partial refund/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Partial refund/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index 75e10b05085..3ffbe03a605 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -89,6 +89,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Recurring Payments - Create/request.json index f6038bfc21b..613e9148f78 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Recurring Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Recurring Payments - Create/request.json @@ -52,6 +52,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, 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 84b93dbf9a2..9df18b5e886 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 @@ -77,6 +77,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json index 913d0b09205..90fe1973d69 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json @@ -52,6 +52,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json index 64a4f8f0440..738179a44db 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json @@ -21,10 +21,6 @@ "amount": 8000, "currency": "USD", "confirm": false, - "routing": { - "type": "single", - "data": "stripe" - }, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, @@ -42,6 +38,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json index 07b3cb1655d..a751c3e522d 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json @@ -77,6 +77,10 @@ "amount": 7000, "quantity": 1 } + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario14-BNPL-affirm/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario14-BNPL-affirm/Payments - Create/request.json index 765651bf169..09867cc8772 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario14-BNPL-affirm/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario14-BNPL-affirm/Payments - Create/request.json @@ -77,6 +77,10 @@ "amount": 7000, "quantity": 1 } + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json index 87d07a6016b..37cd6d0b939 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json @@ -76,6 +76,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json index 87d07a6016b..37cd6d0b939 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json @@ -76,6 +76,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json index 87d07a6016b..37cd6d0b939 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json @@ -76,6 +76,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Redirect-giropay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Redirect-giropay/Payments - Create/request.json index 87d07a6016b..37cd6d0b939 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Redirect-giropay/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Redirect-giropay/Payments - Create/request.json @@ -76,6 +76,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json index 56efdee10c3..eda0801c9cc 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json @@ -76,6 +76,10 @@ "amount": 1800, "account_name": "transaction_processing" } + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Transfer-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Transfer-ach/Payments - Create/request.json index ff8097a532e..38920280c4b 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Transfer-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Transfer-ach/Payments - Create/request.json @@ -38,6 +38,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json index c127e87b06d..abe9c26aeb6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Wallet-Wechatpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Wallet-Wechatpay/Payments - Create/request.json index 2b623eed2ed..daffd2ab9ec 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Wallet-Wechatpay/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Wallet-Wechatpay/Payments - Create/request.json @@ -40,6 +40,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index b41aa02e5d0..785122a83c5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -62,6 +62,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json index f1ff4cb5692..0fbd6a4dcdd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json index f1ff4cb5692..0fbd6a4dcdd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, 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 18cdc9cb92a..b169462ce3d 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 @@ -75,6 +75,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json index 1153185f62c..e9679023b87 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario9-Refund full payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario9-Refund full payment/Payments - Create/request.json index 0d6523e82ba..b5f464abc14 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario9-Refund full payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario9-Refund full payment/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payments - Create/request.json index ca9740f5273..ffaa9907b73 100644 --- a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp Year)/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp Year)/request.json index 41ac0c553fb..5b0df7ad6d0 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp Year)/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp Year)/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/request.json index 29aca608a8a..cbd62dc1327 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/request.json index 0a16b975817..ecfec7e5d60 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/request.json @@ -70,6 +70,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(invalid CVV)/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(invalid CVV)/request.json index 068426b0f35..bed0cc48bc3 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(invalid CVV)/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(invalid CVV)/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index b41aa02e5d0..785122a83c5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -62,6 +62,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/request.json index f1ff4cb5692..0fbd6a4dcdd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario4-Capture the succeeded payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario4-Capture the succeeded payment/Payments - Create/request.json index 0d6523e82ba..b5f464abc14 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario4-Capture the succeeded payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario4-Capture the succeeded payment/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario5-Void the success_slash_failure payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario5-Void the success_slash_failure payment/Payments - Create/request.json index 0d6523e82ba..b5f464abc14 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario5-Void the success_slash_failure payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario5-Void the success_slash_failure payment/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario6-Create 3DS payment with greater capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario6-Create 3DS payment with greater capture/Payments - Create/request.json index 69d9a41d5ab..211364c49ee 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario6-Create 3DS payment with greater capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario6-Create 3DS payment with greater capture/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json index 0d6523e82ba..b5f464abc14 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json index c127e87b06d..abe9c26aeb6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json @@ -72,6 +72,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, 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 75e10b05085..3ffbe03a605 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 @@ -89,6 +89,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json index 6161bc624d8..7046a498b43 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json @@ -64,6 +64,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/.event.meta.json b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/.event.meta.json index 688c85746ef..4ac527d834a 100644 --- a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/.event.meta.json +++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/.event.meta.json @@ -1,5 +1,6 @@ { "eventOrder": [ - "event.test.js" + "event.test.js", + "event.prerequest.js" ] } diff --git a/postman/collection-dir/stripe/event.prerequest.js b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/event.prerequest.js rename to postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.prerequest.js diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/request.json b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/request.json index cf468517b09..5313e3e6b48 100644 --- a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/request.json +++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/request.json @@ -69,7 +69,6 @@ "payment_succeeded_enabled": true, "payment_failed_enabled": true }, - "sub_merchants_enabled": false, "metadata": { "city": "NY", diff --git a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json index 448c0fb9c20..3a060f629d0 100644 --- a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json @@ -84,6 +84,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Payments/.meta.json b/postman/collection-dir/stripe/Payments/.meta.json index afdf2454dac..a0a4e515e53 100644 --- a/postman/collection-dir/stripe/Payments/.meta.json +++ b/postman/collection-dir/stripe/Payments/.meta.json @@ -6,7 +6,7 @@ "Payments - Retrieve", "Payments - Confirm", "Payments - Capture", - "Payments - Create Copy", + "Payments - Create Again", "Payments - Cancel", "Payment-List" ], diff --git a/postman/collection-dir/stripe/Payments/Payments - Create Copy/.event.meta.json b/postman/collection-dir/stripe/Payments/Payments - Create Again/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Payments/Payments - Create Copy/.event.meta.json rename to postman/collection-dir/stripe/Payments/Payments - Create Again/.event.meta.json diff --git a/postman/collection-dir/stripe/Payments/Payments - Create Copy/event.test.js b/postman/collection-dir/stripe/Payments/Payments - Create Again/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Payments/Payments - Create Copy/event.test.js rename to postman/collection-dir/stripe/Payments/Payments - Create Again/event.test.js diff --git a/postman/collection-dir/stripe/Payments/Payments - Create Copy/request.json b/postman/collection-dir/stripe/Payments/Payments - Create Again/request.json similarity index 97% rename from postman/collection-dir/stripe/Payments/Payments - Create Copy/request.json rename to postman/collection-dir/stripe/Payments/Payments - Create Again/request.json index 90c11d5891b..6f9dd5d2615 100644 --- a/postman/collection-dir/stripe/Payments/Payments - Create Copy/request.json +++ b/postman/collection-dir/stripe/Payments/Payments - Create Again/request.json @@ -83,6 +83,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Payments/Payments - Create Copy/response.json b/postman/collection-dir/stripe/Payments/Payments - Create Again/response.json similarity index 100% rename from postman/collection-dir/stripe/Payments/Payments - Create Copy/response.json rename to postman/collection-dir/stripe/Payments/Payments - Create Again/response.json diff --git a/postman/collection-dir/stripe/Payments/Payments - Create/request.json b/postman/collection-dir/stripe/Payments/Payments - Create/request.json index 3a38b8b7e09..9fd202f473d 100644 --- a/postman/collection-dir/stripe/Payments/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Payments/Payments - Create/request.json @@ -83,6 +83,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/QuickStart/Merchant Account - Create/request.json b/postman/collection-dir/stripe/QuickStart/Merchant Account - Create/request.json index 6528126fde1..5313e3e6b48 100644 --- a/postman/collection-dir/stripe/QuickStart/Merchant Account - Create/request.json +++ b/postman/collection-dir/stripe/QuickStart/Merchant Account - Create/request.json @@ -68,7 +68,7 @@ "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true - }, + }, "sub_merchants_enabled": false, "metadata": { "city": "NY", diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/QuickStart/Payments - Create/.event.meta.json index 688c85746ef..4ac527d834a 100644 --- a/postman/collection-dir/stripe/QuickStart/Payments - Create/.event.meta.json +++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/.event.meta.json @@ -1,5 +1,6 @@ { "eventOrder": [ - "event.test.js" + "event.test.js", + "event.prerequest.js" ] } diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.prerequest.js b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json b/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json index 478e0c669db..da1e0039c81 100644 --- a/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/request.json @@ -83,6 +83,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-dir/stripe/Refunds/Payments - Create/request.json b/postman/collection-dir/stripe/Refunds/Payments - Create/request.json index a7d4a2e3cfd..d964f30fcbe 100644 --- a/postman/collection-dir/stripe/Refunds/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Refunds/Payments - Create/request.json @@ -84,6 +84,10 @@ "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" + }, + "routing": { + "type": "single", + "data": "stripe" } } }, diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 64fb0c4c491..367a9b15d0c 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -1,14179 +1,14182 @@ { - "info": { - "_postman_id": "a64a0a71-3270-4f9a-828b-e65f9704739c", - "name": "stripe", - "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "25737662" - }, - "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": "MerchantAccounts", - "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" - } - } - ], - "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": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\" : \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"primary_business_details\": [\n {\n \"country\": \"US\",\n \"business\": \"default\"\n }\n ]\n}", - "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": "Merchant Account - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/: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 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" - } - } - ], - "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": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Retrieve a merchant account details." - }, - "response": [] - }, - { - "name": "Merchant Account - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/: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 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" - } - } - ], - "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": "{\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_name\": \"NewAge Retailer\",\n \"locker_id\": \"m0010\",\n \"merchant_details\": {\n \"primary_contact_person\": \"joseph Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"veniam aute officia ullamco esse\",\n \"secondary_contact_person\": \"joseph Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"proident adipisicing officia nulla\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"parent_merchant_id\": \"xkkdf909012sdjki2dkh5sdf\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "To update an existing merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" - }, - "response": [] - } - ] - }, - { - "name": "API Key", - "item": [ - { - "name": "Create API Key", - "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Update API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_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/:api_key_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": "{\n \"name\": null,\n \"description\": \"My very awesome API key\",\n \"expiration\": null\n}" - }, - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Retrieve API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_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": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api_key_id" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api_key_id", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "List API Keys", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/api_keys/:merchant_id/list - 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": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - "list" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Delete API Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/api_keys/:merchant_id/:api-key", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "api_keys", - ":merchant_id", - ":api-key" - ], - "variable": [ - { - "key": "merchant_id", - "value": "{{merchant_id}}" - }, - { - "key": "api-key", - "value": "{{api_key_id}}" - } - ] - } - }, - "response": [] - } - ] - }, - { - "name": "PaymentConnectors", - "item": [ - { - "name": "Payment Connector - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/accounts/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/accounts/: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" - } - } - ], - "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"business_country\":\"US\",\n \"business_label\":\"default\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\":\"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "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": "Payment Connector - Retrieve", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_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 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" - } - } - ], - "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": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}", - "description": "(Required) The unique identifier for the payment connector" - } - ] - }, - "description": "Retrieve Payment Connector details." - }, - "response": [] - }, - { - "name": "Payment Connector - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - 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/:connector_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 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" - } - } - ], - "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"debit\",\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ],\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n \n {\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" - }, - "response": [] - }, - { - "name": "List Connectors by MID", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/account/:account_id/connectors - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/account/:account_id/connectors - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{admin_api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - } - ] - } - }, - "response": [] - }, - { - "name": "Payment Connector - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_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 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" - } - } - ], - "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": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - ":account_id", - "connectors", - ":connector_id" - ], - "variable": [ - { - "key": "account_id", - "value": "{{merchant_id}}" - }, - { - "key": "connector_id", - "value": "{{merchant_connector_id}}" - } - ] - }, - "description": "Delete or Detach a Payment Connector from Merchant Account" - }, - "response": [] - }, - { - "name": "Merchant Account - Delete", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/accounts/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Response Validation", - "const schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\",\"deleted\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the MerchantAccount object.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"deleted\":{\"type\":\"boolean\",\"description\":\"Indicates the deletion status of the Merchant Account object.\",\"example\":true}}}", - "", - "// Validate if response matches JSON schema ", - "pm.test(\"[DELETE]::/accounts/:id - Schema is valid\", function() {", - " pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});", - "});", - "" - ], - "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": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/accounts/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "accounts", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{merchant_id}}", - "description": "(Required) The unique identifier for the merchant account" - } - ] - }, - "description": "Delete a Merchant Account" - }, - "response": [] - } - ] - }, - { - "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" - } - } - ], - "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": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"primary_business_details\": [\n {\n \"country\": \"US\",\n \"business\": \"default\"\n }\n ]\n}", - "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "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" - } - } - ], - "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"business_country\": \"US\",\n \"business_label\": \"default\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"affirm\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"afterpay_clearpay\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"invoke_sdk_client\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_debit\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"becs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_transfer\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"bacs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"apple_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"google_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"google_pay\": {\n \"allowed_payment_methods\": [\n {\n \"type\": \"CARD\",\n \"parameters\": {\n \"allowed_auth_methods\": [\n \"PAN_ONLY\",\n \"CRYPTOGRAM_3DS\"\n ],\n \"allowed_card_networks\": [\n \"AMEX\",\n \"DISCOVER\",\n \"INTERAC\",\n \"JCB\",\n \"MASTERCARD\",\n \"VISA\"\n ]\n },\n \"tokenization_specification\": {\n \"type\": \"PAYMENT_GATEWAY\",\n \"parameters\": {\n \"gateway\": \"example\",\n \"gateway_merchant_id\": \"{{gateway_merchant_id}}\"\n }\n }\n }\n ],\n \"merchant_info\": {\n \"merchant_name\": \"Narayan Bhat\"\n }\n },\n \"apple_pay\": {\n \"session_token_data\": {\n \"initiative\": \"web\",\n \"certificate\": \"{{certificate}}\",\n \"display_name\": \"applepay\",\n \"certificate_keys\": \"{{certificate_keys}}\",\n \"initiative_context\": \"hyperswitch-sdk-test.netlify.app\",\n \"merchant_identifier\": \"merchant.com.stripe.sang\"\n },\n \"payment_request_data\": {\n \"label\": \"applepay pvt.ltd\",\n \"supported_networks\": [\n \"visa\",\n \"masterCard\",\n \"amex\",\n \"discover\"\n ],\n \"merchant_capabilities\": [\n \"supports3DS\"\n ]\n }\n }\n }\n}", - "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": [ - "// 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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "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.');", - "};", - "" - ], - "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\": 600,\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", - "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": "Customers", - "item": [ - { - "name": "Create Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers - 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]::/customers - 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 \"customer_id\"", - "pm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {", - " pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have a minimum length of \"1\" for \"customer_id\"", - "if (jsonData?.customer_id) {", - "pm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {", - " pm.expect(jsonData.customer_id.length).is.at.least(1);", - "})};", - "", - "", - "// 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.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"First customer\",\n \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}}/customers", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers" - ] - }, - "description": "Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details." - }, - "response": [] - }, - { - "name": "Retrieve Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/customers/: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]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Retrieve a customer's details." - }, - "response": [] - }, - { - "name": "Update Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/customers/: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]::/customers/:id - 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", - "raw": "{\n \"email\": \"[email protected]\",\n \"name\": \"John Test\",\n \"phone_country_code\": \"+65\",\n \"phone\": \"888888888\",\n \"description\": \"First customer\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Updates the customer's details in a customer object." - }, - "response": [] - }, - { - "name": "Ephemeral Key", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/ephemeral_keys - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"customer_id\": \"{{customer_id}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/ephemeral_keys", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "ephemeral_keys" - ] - } - }, - "response": [] - }, - { - "name": "Delete Customer", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[DELETE]::/customers/: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(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "DELETE", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/customers/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "customers", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{customer_id}}", - "description": "(Required) unique customer id" - } - ] - }, - "description": "Delete a customer record." - }, - "response": [] - } - ], - "description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods." - }, - { - "name": "Payments", - "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.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Session Token", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payments/session_tokens - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/session_tokens - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "const responseJson = pm.response.json();", - "", - "// Verify if the wallet_name in the response matches 'apple_pay'", - "pm.test(\"[POST]::/payments/session_tokens - Verify wallet_name is 'apple_pay'\", function() {", - " pm.expect(responseJson.session_token[0].wallet_name).to.eql(\"apple_pay\");", - "});", - "", - "// Verify if the wallet_name in the response matches 'google_pay'", - "pm.test(\"[POST]::/payments/session_tokens - Verify wallet_name is 'google_pay'\", function() {", - " pm.expect(responseJson.session_token[1].wallet_name).to.eql(\"google_pay\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{publishable_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"wallets\":[],\n \"client_secret\": \"{{client_secret}}\"\n}" - }, - "url": { - "raw": "{{baseUrl}}/payments/session_tokens", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "session_tokens" - ] - } - }, - "response": [] - }, - { - "name": "Payments - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// 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();", - "});", - "", - "", - "// 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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 20000,\n \"currency\": \"SGD\",\n \"confirm\" :false,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"email\": \"[email protected]\",\n \"name\": \"joseph Doe\",\n \"phone\": \"8888888888\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"payment_method\": \"card\",\n \"return_url\": \"https://duck.com\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "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 " - }, - "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.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "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\");", - "});", - "", - "", - "", - "// 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.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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.');", - "};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 6540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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 - Create Copy", - "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.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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", - "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();", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment 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" - }, - "response": [] - }, - { - "name": "Payment-List", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[GET]::/payments/list - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/list - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "api-key", - "value": "snd_0b8e1deb82f241eca47617afb1398858" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/list", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "list" - ], - "query": [ - { - "key": "customer_id", - "value": "", - "disabled": true - }, - { - "key": "starting_after", - "value": "", - "disabled": true - }, - { - "key": "ending_before", - "value": "", - "disabled": true - }, - { - "key": "limit", - "value": "100", - "disabled": true - }, - { - "key": "created", - "value": "", - "disabled": true - }, - { - "key": "created.lt", - "value": "", - "disabled": true - }, - { - "key": "created.gt", - "value": "", - "disabled": true - }, - { - "key": "created.lte", - "value": "", - "disabled": true - }, - { - "key": "created_gte", - "value": "", - "disabled": true - } - ] - } - }, - "response": [] - } - ], - "description": "Process and manage payments across wide range of payment processors using the Unified Payments API." - }, - { - "name": "Refunds", - "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.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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.');", - "};", - "" - ], - "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\": 600,\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 - Update", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/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": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"reason\": \"Paid by mistake\",\n \"metadata\": {\n \"udf1\": \"value2\",\n \"new_customer\": \"false\",\n \"login_date\": \"2019-09-1T10:11:12Z\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" - }, - "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", - "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": "PaymentMethods", - "item": [ - { - "name": "PaymentMethods - Create", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 2xx ", - "pm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payment_methods - 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_method_id as variable for jsonData.payment_method_id", - "if (jsonData?.payment_method_id) {", - " pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);", - " console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id 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", - "raw": "{\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_issuer\": \"Visa\",\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"John Doe\"\n },\n \"customer_id\": \"cus_mnewerunwiuwiwqw\",\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payment_methods", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payment_methods" - ] - }, - "description": "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" - }, - "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\");", - "});", - "", - "" - ], - "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" - } - ], - "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 - 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"debit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 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": "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" - } - } - ], - "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": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"primary_business_details\": [\n {\n \"country\": \"US\",\n \"business\": \"default\"\n }\n ]\n}", - "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": "{\n \"name\": \"API Key 1\",\n \"description\": null,\n \"expiration\": \"2023-09-23T01:02:03.000Z\"\n}" - }, - "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" - } - } - ], - "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": "{\n \"connector_type\": \"fiz_operations\",\n \"connector_name\": \"stripe\",\n \"business_country\": \"US\",\n \"business_label\": \"default\",\n \"connector_account_details\": {\n \"auth_type\": \"HeaderKey\",\n \"api_key\": \"{{connector_api_key}}\"\n },\n \"test_mode\": false,\n \"disabled\": false,\n \"payment_methods_enabled\": [\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"affirm\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"afterpay_clearpay\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"pay_later\",\n \"payment_method_types\": [\n {\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"payment_experience\": \"invoke_sdk_client\",\n \"payment_method_type\": \"klarna\"\n }\n ]\n },\n {\n \"payment_method\": \"bank_redirect\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ideal\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"giropay\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sofort\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"eps\",\n \"payment_experience\": null,\n \"card_networks\": null,\n \"accepted_currencies\": null,\n \"accepted_countries\": null,\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_debit\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"becs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"bank_transfer\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"ach\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"bacs\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"sepa\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"credit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ]\n }\n ]\n },\n {\n \"payment_method\": \"card\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"debit\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true,\n \"card_networks\": [\n \"Visa\",\n \"Mastercard\"\n ]\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"apple_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n },\n {\n \"payment_method\": \"wallet\",\n \"payment_method_types\": [\n {\n \"payment_method_type\": \"google_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n },\n {\n \"payment_method_type\": \"we_chat_pay\",\n \"payment_experience\": \"invoke_sdk_client\",\n \"minimum_amount\": 1,\n \"maximum_amount\": 68607706,\n \"recurring_enabled\": true,\n \"installment_payment_enabled\": true\n }\n ]\n }\n ],\n \"metadata\": {\n \"google_pay\": {\n \"allowed_payment_methods\": [\n {\n \"type\": \"CARD\",\n \"parameters\": {\n \"allowed_auth_methods\": [\n \"PAN_ONLY\",\n \"CRYPTOGRAM_3DS\"\n ],\n \"allowed_card_networks\": [\n \"AMEX\",\n \"DISCOVER\",\n \"INTERAC\",\n \"JCB\",\n \"MASTERCARD\",\n \"VISA\"\n ]\n },\n \"tokenization_specification\": {\n \"type\": \"PAYMENT_GATEWAY\",\n \"parameters\": {\n \"gateway\": \"example\",\n \"gateway_merchant_id\": \"{{gateway_merchant_id}}\"\n }\n }\n }\n ],\n \"merchant_info\": {\n \"merchant_name\": \"Narayan Bhat\"\n }\n },\n \"apple_pay\": {\n \"session_token_data\": {\n \"initiative\": \"web\",\n \"certificate\": \"{{certificate}}\",\n \"display_name\": \"applepay\",\n \"certificate_keys\": \"{{certificate_keys}}\",\n \"initiative_context\": \"hyperswitch-sdk-test.netlify.app\",\n \"merchant_identifier\": \"merchant.com.stripe.sang\"\n },\n \"payment_request_data\": {\n \"label\": \"applepay pvt.ltd\",\n \"supported_networks\": [\n \"visa\",\n \"masterCard\",\n \"amex\",\n \"discover\"\n ],\n \"merchant_capabilities\": [\n \"supports3DS\"\n ]\n }\n }\n }\n}", - "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": [ - "// 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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" - }, - "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.');", - "};", - "" - ], - "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\": 600,\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", - "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": "Happy Cases", - "item": [ - { - "name": "Scenario1-Create payment with confirm true", - "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.');", - "};", - "", - "// 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;", - "});", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"business_country\": \"US\",\n \"business_label\": \"default\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1,\n \"customer_id\": \"bernard123\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"setup_future_usage\": \"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"debit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"01\",\n \"card_exp_year\": \"24\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\",\n \"last_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\",\n \"last_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"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": "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": "Scenario2-Create payment with confirm false", - "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.');", - "};", - "", - "// Response body should have value \"requires_confirmation\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", - "})};", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// 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 \"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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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 \"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\");", - "})};" - ], - "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": "Scenario3-Create payment without PMD", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// 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 \"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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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 \"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\");", - "})};" - ], - "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": "Scenario4-Create 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.');", - "};", - "", - "// Response body should have value \"requires_capture\" 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\");", - "})};", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - 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\");", - "})};", - "", - "// 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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 6000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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", - "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": "Scenario5-Void the payment", - "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.');", - "};", - "", - "// Response body should have value \"requires_capture\" 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\");", - "})};", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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", - "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();", - "});", - "", - "// 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 \"cancelled\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\", function() {", - " pm.expect(jsonData.status).to.eql(\"cancelled\");", - "})};", - "", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment 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" - }, - "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 \"cancelled\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\", function() {", - " pm.expect(jsonData.status).to.eql(\"cancelled\");", - "})};" - ], - "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": "Scenario6-Create 3DS payment", - "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.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "// Response body should have \"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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"business_country\":\"US\",\n \"business_label\" : \"default\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"setup_future_usage\":\"on_session\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"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\");", - "})};", - "" - ], - "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": "Scenario7-Create 3DS payment with confrm false", - "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.');", - "};", - "", - "// Response body should have value \"requires_confirmation\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", - "})};", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments/: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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario9-Refund full payment", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", - "})};", - "" - ], - "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'\", 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 '6540'\", function() {", - " pm.expect(jsonData.amount).to.eql(6540);", - "})};", - "" - ], - "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\": 6540,\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.');", - "};", - "", - "// 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 '6540'\", function() {", - " pm.expect(jsonData.amount).to.eql(6540);", - "})};", - "" - ], - "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": "Scenario10-Partial refund", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", - "})};", - "" - ], - "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'\", 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);", - "})};", - "" - ], - "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\": 540,\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.');", - "};", - "", - "// 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 '540'\", function() {", - " pm.expect(jsonData.amount).to.eql(540);", - "})};", - "" - ], - "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": "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'\", function() {", - " pm.expect(jsonData.status).to.eql(\"succeeded\");", - "})};", - "", - "// 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);", - "})};", - "" - ], - "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\": 1000,\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.');", - "};", - "", - "// 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 '1000'\", function() {", - " pm.expect(jsonData.amount).to.eql(1000);", - "})};", - "" - ], - "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": "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 \"refunds\"", - "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function() {", - " pm.expect((typeof jsonData.refunds !== \"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-Create a mandate and recurring payment", - "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.');", - "};", - "", - "// 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\"", - "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\", 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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\", 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Scenario11-Refund recurring payment", - "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.');", - "};", - "", - "// 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\"", - "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\", 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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\"", - "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\", 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", - "raw": "{\n \"amount\": 6570,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "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 \"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);", - "})};", - "" - ], - "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\": 6540,\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 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 '6540'\", function() {", - " pm.expect(jsonData.amount).to.eql(6540);", - "})};", - "" - ], - "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-BNPL-klarna", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 8000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n },\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"klarna_redirect\": {\n \"issuer_name\": \"stripe\",\n \"billing_email\": \"[email protected]\",\n \"billing_country\": \"US\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario13-BNPL-afterpay", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 7000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"country\": \"SE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"SE\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"order_details\": {\n \"product_name\": \"Socks\",\n \"amount\": 7000,\n \"quantity\": 1\n }\n }\n}", - "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 - 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_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'afterpay_clearpay'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"afterpay_clearpay\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"afterpay_clearpay_redirect\": {\n \"billing_name\": \"Akshaya\",\n \"billing_email\": \"[email protected]\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario14-BNPL-affirm", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 7000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"country\": \"US\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"order_details\": {\n \"product_name\": \"Socks\",\n \"amount\": 7000,\n \"quantity\": 1\n }\n }\n}", - "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 - 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_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'affirm'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"affirm\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"affirm_redirect\": {\n \"issuer_name\": \"affirm\",\n \"billing_email\": \"[email protected]\",\n \"billing_country\": \"US\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario15-Bank Redirect-Ideal", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'ideal'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"ideal\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"ideal\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"ing\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario16-Bank Redirect-sofort", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'sofort'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"sofort\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"sofort\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"hypo_noe_lb_fur_niederosterreich_u_wien\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario17-Bank Redirect-eps", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'eps'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"eps\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"eps\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"hypo_oberosterreich_salzburg_steiermark\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario18-Bank Redirect-giropay", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"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\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", - " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"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 'giropay'\", function() {", - " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");", - "})};", - "", - "", - "// 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": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"giropay\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"giropay\": {\n \"billing_details\": {\n \"billing_name\": \"John Doe\"\n },\n \"bank_name\": \"\",\n \"preferred_language\": \"en\",\n \"country\": \"DE\"\n }\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario19-Bank Transfer-ach", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 800,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 800,\n \"customer_id\": \"poll\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://hs-payments-test.netlify.app/payments\",\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"bank_transfer\",\n \"payment_method_type\": \"ach\",\n \"payment_method_data\": {\n \"bank_transfer\": {\n \"ach_bank_transfer\": {\n \"billing_details\": {\n \"email\": \"[email protected]\"\n }\n }\n }\n }\n\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Scenario19-Bank Debit-ach", - "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.');", - "};", - "", - "// 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" - } - }, - { - "listen": "prerequest", - "script": { - "exec": [ - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 1800,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"business_label\": \"default\",\n \"capture_method\": \"automatic\",\n \"connector\": [\n \"stripe\"\n ],\n \"customer_id\": \"klarna\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"authentication_type\": \"three_ds\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"return_url\": \"https://google.com\",\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\n \"setup_future_usage\": \"off_session\",\n \"business_country\": \"US\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"online\",\n \"accepted_at\": \"2022-09-10T10:11:12Z\",\n \"online\": {\n \"ip_address\": \"123.32.25.123\",\n \"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\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 6540,\n \"currency\": \"USD\"\n }\n }\n },\n \"payment_method\": \"bank_debit\",\n \"payment_method_type\": \"ach\",\n \"payment_method_data\": {\n \"bank_debit\": {\n \"ach_bank_debit\": {\n \"billing_details\": {\n \"name\": \"John Doe\",\n \"email\": \"[email protected]\"\n },\n \"account_number\": \"000123456789\",\n \"routing_number\": \"110000000\"\n }\n }\n },\n \"metadata\": {\n \"order_details\": {\n \"product_name\": \"Apple iphone 15\",\n \"quantity\": 1,\n \"amount\": 1800,\n \"account_name\": \"transaction_processing\"\n }\n }\n}", - "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]::/payments/:id - Status code is 2xx\", function () {", - " pm.response.to.be.success;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};" - ], - "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": "Scenario22-Wallet-Wechatpay", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 800,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"business_country\":\"US\",\n \"business_label\":\"default\",\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 800,\n \"customer_id\": \"poll\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"statement_descriptor_name\": \"Juspay\",\n \"statement_descriptor_suffix\": \"Router\",\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}}/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;", - "});", - "", - "// Validate if response header has matching content-type", - "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {", - " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", - "});", - "", - "", - "", - "// Validate if response has JSON Body ", - "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {", - " pm.response.to.have.jsonBody();", - "});", - "", - "", - "// Set response object as internal variable", - "let jsonData = {};", - "try {jsonData = pm.response.json();}catch(e){}", - "", - "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", - "if (jsonData?.payment_id) {", - " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", - " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", - "};", - "", - "", - "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", - "if (jsonData?.mandate_id) {", - " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", - " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", - "} else {", - " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", - "};", - "", - "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", - "if (jsonData?.client_secret) {", - " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", - " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", - "} else {", - " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "", - "// Response body should have \"next_action.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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"payment_method\": \"wallet\",\n \"payment_method_type\": \"we_chat_pay\",\n \"payment_method_data\": {\n \"wallet\": {\n \"we_chat_pay_qr\": {}\n }\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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\"", - "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\");", - "})};" - ], - "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": "Variation Cases", - "item": [ - { - "name": "Scenario1-Create payment with Invalid card details", - "item": [ - { - "name": "Payments - Create(Invalid card number)", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", - "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector_error'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"connector_error\");", - "})};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"123456\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"united states\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"united states\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 Exp month)", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"01\",\n \"card_exp_year\": \"2023\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 Exp Year)", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", - "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "// Response body should have value \"connector error\" for \"error message\"", - "if (jsonData?.error?.message) {", - "pm.test(\"[POST]::/payments - Content check if value for 'error.message' matches '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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"2022\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", - "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"connector\");", - "})};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"123456\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"12345\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "Scenario2-Confirming the payment without PMD", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": " {}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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": "Scenario3-Capture greater amount", - "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.');", - "};", - "", - "// Response body should have value \"requires_capture\" 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\");", - "})};", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - Capture", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 7000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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 \"requires_capture\" 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\");", - "})};" - ], - "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": "Scenario4-Capture the succeeded payment", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 - Capture", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 7000,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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": "Scenario5-Void the success/failure payment", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 4xx ", - "pm.test(\"[POST]::/payments/:id/cancel - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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();", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "", - "", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"cancellation_reason\": \"requested_by_customer\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/cancel", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "cancel" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment 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" - }, - "response": [] - } - ] - }, - { - "name": "Scenario6-Create 3DS payment with greater 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.');", - "};", - "", - "// Response body should have value \"requires_customer_action\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", - "})};", - "", - "// Response body should have \"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" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"manual\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4000000000003063\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"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\");", - "})};" - ], - "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": "Payments - Capture", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "", - "", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount_to_capture\": 7540,\n \"statement_descriptor_name\": \"Joseph\",\n \"statement_descriptor_suffix\": \"JS\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "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": "Scenario7-Refund exceeds amount", - "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.');", - "};", - "", - "// 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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\");", - "})};", - "" - ], - "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 4xx ", - "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"connector error\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "" - ], - "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\": 7000,\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": "Scenario8-Refund for unsuccessful payment", - "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.');", - "};", - "", - "// Response body should have value \"requires_confirmation\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", - "})};", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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 \"requires_confirmation\" for \"status\"", - "if (jsonData?.status) {", - "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", - "})};", - "" - ], - "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 4xx ", - "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", - " pm.response.to.be.error;", - "});", - "", - "// 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 \"error\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"invalid_request\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "" - ], - "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\": 540,\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": "Scenario9-Create a recurring payment with greater mandate amount", - "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.');", - "};", - "", - "// 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\"", - "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\", 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", - "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"setup_future_usage\": \"off_session\",\n \"mandate_data\": {\n \"customer_acceptance\": {\n \"acceptance_type\": \"offline\",\n \"accepted_at\": \"1963-05-03T04:07:52.723Z\",\n \"online\": {\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"amet irure esse\"\n }\n },\n \"mandate_type\": {\n \"single_use\": {\n \"amount\": 7000,\n \"currency\": \"USD\"\n }\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": "test", - "script": { - "exec": [ - "// Validate status 4xx ", - "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", - " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", - "});", - "", - "// Response body should have value \"invalid_request\" for \"error type\"", - "if (jsonData?.error?.type) {", - "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", - " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", - "})};", - "", - "", - "" - ], - "type": "text/javascript" - } - } - ], - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"amount\": 8040,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"mandate_id\" : \"{{mandate_id}}\",\n \"off_session\" : true,\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"sundari\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\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}}/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": { - "type": "text/javascript", - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "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'));", - "" - ] - } - } - ], - "variable": [ - { - "key": "baseUrl", - "value": "", - "type": "string" - }, - { - "key": "admin_api_key", - "value": "", - "type": "string" - }, - { - "key": "api_key", - "value": "", - "type": "string" - }, - { - "key": "merchant_id", - "value": "" - }, - { - "key": "payment_id", - "value": "" - }, - { - "key": "customer_id", - "value": "" - }, - { - "key": "mandate_id", - "value": "" - }, - { - "key": "payment_method_id", - "value": "" - }, - { - "key": "refund_id", - "value": "" - }, - { - "key": "merchant_connector_id", - "value": "" - }, - { - "key": "client_secret", - "value": "", - "type": "string" - }, - { - "key": "connector_api_key", - "value": "", - "type": "string" - }, - { - "key": "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" - } - ] -} + "info": { + "_postman_id": "b4f11b9e-244e-4f34-b5dd-418dcdc91699", + "name": "Stripe Collection", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "25737662" + }, + "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": "MerchantAccounts", + "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": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com/success\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n },\n \"primary_business_details\": [\n {\n \"country\": \"US\",\n \"business\": \"default\"\n }\n ]\n}", + "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": "Merchant Account - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/accounts/: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 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" + } + } + ], + "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": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Retrieve a merchant account details." + }, + "response": [] + }, + { + "name": "Merchant Account - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts/: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 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" + } + } + ], + "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\":\"{{merchant_id}}\",\"merchant_name\":\"NewAge Retailer\",\"locker_id\":\"m0010\",\"merchant_details\":{\"primary_contact_person\":\"joseph Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"veniam aute officia ullamco esse\",\"secondary_contact_person\":\"joseph Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"proident adipisicing officia nulla\",\"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,\"parent_merchant_id\":\"xkkdf909012sdjki2dkh5sdf\",\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "To update an existing merchant account. Helpful in updating merchant details such as email, contact deteails, or other configuration details like webhook, routing algorithm etc" + }, + "response": [] + } + ] + }, + { + "name": "API Key", + "item": [ + { + "name": "Create API Key", + "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\":\"2023-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": "Update API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/api_keys/:merchant_id/:api_key_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/:api_key_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\":null,\"description\":\"My very awesome API key\",\"expiration\":null}" + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api_key_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api_key_id", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Retrieve API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/api_keys/:merchant_id/:api_key_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": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api_key_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api_key_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api_key_id", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "List API Keys", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/api_keys/:merchant_id/list - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/api_keys/:merchant_id/list - 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": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/list", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + "list" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Delete API Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/api_keys/:merchant_id/:api-key - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id/:api-key", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id", + ":api-key" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + }, + { + "key": "api-key", + "value": "{{api_key_id}}" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "PaymentConnectors", + "item": [ + { + "name": "Payment Connector - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/accounts/:account_id/connectors - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts/: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" + } + } + ], + "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\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"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\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}", + "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": "Payment Connector - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/accounts/:account_id/connectors/:connector_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 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" + } + } + ], + "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": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}", + "description": "(Required) The unique identifier for the payment connector" + } + ] + }, + "description": "Retrieve Payment Connector details." + }, + "response": [] + }, + { + "name": "Payment Connector - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/account/:account_id/connectors/:connector_id - 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/:connector_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 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" + } + } + ], + "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\":\"fiz_operations\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"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\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}" + } + ] + }, + "description": "To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc" + }, + "response": [] + }, + { + "name": "List Connectors by MID", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/account/:account_id/connectors - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/account/:account_id/connectors - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Payment Connector - Delete", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/account/:account_id/connectors/:connector_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 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" + } + } + ], + "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": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors", + ":connector_id" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}" + }, + { + "key": "connector_id", + "value": "{{merchant_connector_id}}" + } + ] + }, + "description": "Delete or Detach a Payment Connector from Merchant Account" + }, + "response": [] + }, + { + "name": "Merchant Account - Delete", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/accounts/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/accounts/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Response Validation", + "const schema = {\"type\":\"object\",\"description\":\"Merchant Account\",\"required\":[\"merchant_id\",\"deleted\"],\"properties\":{\"merchant_id\":{\"type\":\"string\",\"description\":\"The identifier for the MerchantAccount object.\",\"maxLength\":255,\"example\":\"y3oqhf46pyzuxjbcn2giaqnb44\"},\"deleted\":{\"type\":\"boolean\",\"description\":\"Indicates the deletion status of the Merchant Account object.\",\"example\":true}}}", + "", + "// Validate if response matches JSON schema ", + "pm.test(\"[DELETE]::/accounts/:id - Schema is valid\", function() {", + " pm.response.to.have.jsonSchema(schema,{unknownFormats: [\"int32\", \"int64\", \"float\", \"double\"]});", + "});", + "" + ], + "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": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/accounts/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Delete a Merchant Account" + }, + "response": [] + } + ] + }, + { + "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" + } + } + ], + "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\",\"merchant_details\":{\"primary_contact_person\":\"John Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"cillum do dolor id\",\"website\":\"www.example.com\",\"about_business\":\"Online Retail with a wide selection of organic products for North America\",\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"return_url\":\"https://duck.com/success\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"webhook_username\":\"ekart_retail\",\"webhook_password\":\"password_ekart@123\",\"payment_created_enabled\":true,\"payment_succeeded_enabled\":true,\"payment_failed_enabled\":true},\"sub_merchants_enabled\":false,\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"},\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}]}", + "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\":\"2023-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" + } + } + ], + "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\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"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\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"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},{\"payment_method_type\":\"giropay\",\"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},{\"payment_method_type\":\"sofort\",\"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},{\"payment_method_type\":\"eps\",\"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}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"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\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"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\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}", + "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": [ + "// 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": [], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"amount\": 6540,\n \"currency\": \"USD\",\n \"confirm\": true,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+1\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"payment_method\": \"card\",\n \"payment_method_type\": \"credit\",\n \"payment_method_data\": {\n \"card\": {\n \"card_number\": \"4242424242424242\",\n \"card_exp_month\": \"10\",\n \"card_exp_year\": \"25\",\n \"card_holder_name\": \"joseph Doe\",\n \"card_cvc\": \"123\"\n }\n },\n \"billing\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"joseph\",\n \"last_name\": \"Doe\"\n },\n \"phone\": {\n \"number\": \"8056594427\",\n \"country_code\": \"+91\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n },\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"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\"}}", + "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", + "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": "Customers", + "item": [ + { + "name": "Create Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/customers - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/customers - 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]::/customers - 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 \"customer_id\"", + "pm.test(\"[POST]::/customers - Content check if 'customer_id' exists\", function() {", + " pm.expect((typeof jsonData.customer_id !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have a minimum length of \"1\" for \"customer_id\"", + "if (jsonData?.customer_id) {", + "pm.test(\"[POST]::/customers - Content check if value of 'customer_id' has a minimum length of '1'\", function() {", + " pm.expect(jsonData.customer_id.length).is.at.least(1);", + "})};", + "", + "", + "// 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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"First customer\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/customers", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers" + ] + }, + "description": "Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details." + }, + "response": [] + }, + { + "name": "Retrieve Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/customers/: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]::/customers/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Retrieve a customer's details." + }, + "response": [] + }, + { + "name": "Update Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/customers/: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]::/customers/:id - 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", + "raw": "{\"email\":\"[email protected]\",\"name\":\"John Test\",\"phone_country_code\":\"+65\",\"phone\":\"888888888\",\"description\":\"First customer\",\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Updates the customer's details in a customer object." + }, + "response": [] + }, + { + "name": "Ephemeral Key", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/ephemeral_keys - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"customer_id\":\"{{customer_id}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/ephemeral_keys", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "ephemeral_keys" + ] + } + }, + "response": [] + }, + { + "name": "Delete Customer", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[DELETE]::/customers/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[DELETE]::/customers/: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(\"[DELETE]::/customers/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/customers/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "customers", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{customer_id}}", + "description": "(Required) unique customer id" + } + ] + }, + "description": "Delete a customer record." + }, + "response": [] + } + ], + "description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods." + }, + { + "name": "Payments", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": "Session Token", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payments/session_tokens - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments/session_tokens - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "const responseJson = pm.response.json();", + "", + "// Verify if the wallet_name in the response matches 'apple_pay'", + "pm.test(\"[POST]::/payments/session_tokens - Verify wallet_name is 'apple_pay'\", function() {", + " pm.expect(responseJson.session_token[0].wallet_name).to.eql(\"apple_pay\");", + "});", + "", + "// Verify if the wallet_name in the response matches 'google_pay'", + "pm.test(\"[POST]::/payments/session_tokens - Verify wallet_name is 'google_pay'\", function() {", + " pm.expect(responseJson.session_token[1].wallet_name).to.eql(\"google_pay\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{publishable_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"payment_id\":\"{{payment_id}}\",\"wallets\":[],\"client_secret\":\"{{client_secret}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/payments/session_tokens", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + "session_tokens" + ] + } + }, + "response": [] + }, + { + "name": "Payments - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// 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();", + "});", + "", + "", + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":20000,\"currency\":\"SGD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"email\":\"[email protected]\",\"name\":\"joseph Doe\",\"phone\":\"8888888888\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"payment_method\":\"card\",\"return_url\":\"https://duck.com\",\"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\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "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 " + }, + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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\");", + "});", + "", + "", + "", + "// 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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 - Create Again", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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", + "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();", + "});", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "response": [] + }, + { + "name": "Payment-List", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[GET]::/payments/list - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/list - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "api-key", + "value": "snd_0b8e1deb82f241eca47617afb1398858" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/list", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + "list" + ], + "query": [ + { + "key": "customer_id", + "value": "", + "disabled": true + }, + { + "key": "starting_after", + "value": "", + "disabled": true + }, + { + "key": "ending_before", + "value": "", + "disabled": true + }, + { + "key": "limit", + "value": "100", + "disabled": true + }, + { + "key": "created", + "value": "", + "disabled": true + }, + { + "key": "created.lt", + "value": "", + "disabled": true + }, + { + "key": "created.gt", + "value": "", + "disabled": true + }, + { + "key": "created.lte", + "value": "", + "disabled": true + }, + { + "key": "created_gte", + "value": "", + "disabled": true + } + ] + } + }, + "response": [] + } + ], + "description": "Process and manage payments across wide range of payment processors using the Unified Payments API." + }, + { + "name": "Refunds", + "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.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": "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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"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\"}}", + "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 - Update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/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": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"reason\":\"Paid by mistake\",\"metadata\":{\"udf1\":\"value2\",\"new_customer\":\"false\",\"login_date\":\"2019-09-1T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields" + }, + "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", + "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": "PaymentMethods", + "item": [ + { + "name": "PaymentMethods - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx ", + "pm.test(\"[POST]::/payment_methods - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payment_methods - 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_method_id as variable for jsonData.payment_method_id", + "if (jsonData?.payment_method_id) {", + " pm.collectionVariables.set(\"payment_method_id\", jsonData.payment_method_id);", + " console.log(\"- use {{payment_method_id}} as collection variable for value\",jsonData.payment_method_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_method_id}}, as jsonData.payment_method_id 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", + "raw": "{\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_issuer\":\"Visa\",\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"John Doe\"},\"customer_id\":\"cus_mnewerunwiuwiwqw\",\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payment_methods", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payment_methods" + ] + }, + "description": "To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants" + }, + "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\");", + "});", + "", + "" + ], + "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" + } + ], + "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 - 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": "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": "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" + } + } + ], + "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\",\"merchant_details\":{\"primary_contact_person\":\"John Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"cillum do dolor id\",\"website\":\"www.example.com\",\"about_business\":\"Online Retail with a wide selection of organic products for North America\",\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"return_url\":\"https://duck.com\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"webhook_username\":\"ekart_retail\",\"webhook_password\":\"password_ekart@123\",\"payment_created_enabled\":true,\"payment_succeeded_enabled\":true,\"payment_failed_enabled\":true},\"sub_merchants_enabled\":false,\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"},\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}]}", + "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\":\"2023-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" + } + } + ], + "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\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"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\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"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},{\"payment_method_type\":\"giropay\",\"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},{\"payment_method_type\":\"sofort\",\"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},{\"payment_method_type\":\"eps\",\"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}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"Visa\",\"Mastercard\"]}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"Visa\",\"Mastercard\"]}]},{\"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\":\"wallet\",\"payment_method_types\":[{\"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_type\":\"we_chat_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"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\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}", + "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": [ + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment id" + } + ] + }, + "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "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.');", + "};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"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\"}}", + "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", + "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": "Happy Cases", + "item": [ + { + "name": "Scenario1-Create payment with confirm true", + "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.');", + "};", + "", + "// 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;", + "});", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\":\"24\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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 \"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": "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": "Scenario2-Create payment with confirm false", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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 \"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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"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\");", + "})};" + ], + "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": "Scenario3-Create payment without PMD", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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 \"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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"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\");", + "})};" + ], + "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": "Scenario4-Create 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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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\");", + "})};", + "", + "// 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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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", + "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": "Scenario5-Void the payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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", + "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();", + "});", + "", + "// 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 \"cancelled\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\", function() {", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "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 \"cancelled\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\", function() {", + " pm.expect(jsonData.status).to.eql(\"cancelled\");", + "})};" + ], + "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": "Scenario6-Create 3DS payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "", + "};", + "", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "" + ], + "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": "Scenario7-Create 3DS payment with confrm false", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments/: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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario9-Refund full payment", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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\");", + "})};", + "" + ], + "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'\", 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}", + "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.');", + "};", + "", + "// 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "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": "Scenario10-Partial refund", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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\");", + "})};", + "" + ], + "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'\", 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);", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}", + "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.');", + "};", + "", + "// 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 '540'\", function() {", + " pm.expect(jsonData.amount).to.eql(540);", + "})};", + "" + ], + "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": "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 \"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);", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}", + "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-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 '1000'\", function() {", + " pm.expect(jsonData.amount).to.eql(1000);", + "})};", + "" + ], + "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": "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 \"refunds\"", + "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function() {", + " pm.expect((typeof jsonData.refunds !== \"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-Create a mandate and recurring payment", + "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.');", + "};", + "", + "// 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\"", + "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\", 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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": "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 \"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\", 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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-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": "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 \"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\"", + "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\", 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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": "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 \"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\"", + "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\", 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", + "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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-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 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 \"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);", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}", + "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 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 '6540'\", function() {", + " pm.expect(jsonData.amount).to.eql(6540);", + "})};", + "" + ], + "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-BNPL-klarna", + "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.');", + "};", + "", + "// 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", + "raw": "{\n \"amount\": 8000,\n \"currency\": \"USD\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 6540,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"no_three_ds\",\n \"return_url\": \"https://duck.com\",\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n },\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_method\": \"pay_later\",\n \"payment_method_type\": \"klarna\",\n \"payment_experience\": \"redirect_to_url\",\n \"payment_method_data\": {\n \"pay_later\": {\n \"klarna_redirect\": {\n \"issuer_name\": \"stripe\",\n \"billing_email\": \"[email protected]\",\n \"billing_country\": \"US\"\n }\n }\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario13-BNPL-afterpay", + "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.');", + "};", + "", + "// 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", + "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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}},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'afterpay_clearpay'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario14-BNPL-affirm", + "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.');", + "};", + "", + "// 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", + "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://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}},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'affirm'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"billing_country\":\"US\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario15-Bank Redirect-Ideal", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'ideal'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario16-Bank Redirect-sofort", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'sofort'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario17-Bank Redirect-eps", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'eps'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario18-Bank Redirect-giropay", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "", + "// Response body should have \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {", + " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"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 'giropay'\", function() {", + " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");", + "})};", + "", + "", + "// 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": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario19-Bank Transfer-ach", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_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 '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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_transfer\":{\"ach_bank_transfer\":{\"billing_details\":{\"email\":\"[email protected]\"}}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Scenario19-Bank Debit-ach", + "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.');", + "};", + "", + "// 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" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"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\":\"[email protected]\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};" + ], + "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": "Scenario22-Wallet-Wechatpay", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - 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_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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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\"", + "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\");", + "})};" + ], + "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": "Variation Cases", + "item": [ + { + "name": "Scenario1-Create payment with Invalid card details", + "item": [ + { + "name": "Payments - Create(Invalid card number)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector_error'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector_error\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"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\":\"united states\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"united states\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 Exp month)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"2023\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 Exp Year)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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 \"next_action.redirect_to_url\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "// Response body should have value \"connector error\" for \"error message\"", + "if (jsonData?.error?.message) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.message' matches '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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2022\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"connector\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": "Scenario2-Confirming the payment without PMD", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - Confirm", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario3-Capture greater amount", + "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.');", + "};", + "", + "// Response body should have value \"requires_capture\" 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\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":7000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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 \"requires_capture\" 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\");", + "})};" + ], + "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": "Scenario4-Capture the succeeded payment", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":7000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario5-Void the success_slash_failure payment", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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 - Cancel", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/cancel - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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();", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"cancellation_reason\":\"requested_by_customer\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments/:id/cancel", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id", + "cancel" + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique payment 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" + }, + "response": [] + } + ] + }, + { + "name": "Scenario6-Create 3DS payment with greater 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.');", + "};", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};", + "", + "// Response body should have \"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" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/payments/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");", + "});", + "", + "// Validate if response has JSON Body ", + "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {jsonData = pm.response.json();}catch(e){}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');", + "};", + "", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);", + "} else {", + " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');", + "};", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);", + "} else {", + " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');", + "};", + "", + "", + "// Response body should have value \"requires_customer_action\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");", + "})};" + ], + "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": "Payments - Capture", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount_to_capture\":7540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "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": "Scenario7-Refund exceeds amount", + "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.');", + "};", + "", + "// 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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\");", + "})};", + "" + ], + "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 4xx ", + "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"connector error\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":7000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + } + ] + }, + { + "name": "Scenario8-Refund for unsuccessful payment", + "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.');", + "};", + "", + "// Response body should have value \"requires_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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_confirmation\" for \"status\"", + "if (jsonData?.status) {", + "pm.test(\"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\", function() {", + " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + "})};", + "" + ], + "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 4xx ", + "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {", + " pm.response.to.be.error;", + "});", + "", + "// 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 \"error\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "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\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + } + ] + }, + { + "name": "Scenario9-Create a recurring payment with greater mandate amount", + "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.');", + "};", + "", + "// 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\"", + "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\", 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", + "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\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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]::/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": "test", + "script": { + "exec": [ + "// Validate status 4xx ", + "pm.test(\"[POST]::/payments - Status code is 4xx\", 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.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\"", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if 'error' exists\", function() {", + " pm.expect((typeof jsonData.error !== \"undefined\")).to.be.true;", + "});", + "", + "// Response body should have value \"invalid_request\" for \"error type\"", + "if (jsonData?.error?.type) {", + "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\", function() {", + " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");", + "})};", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":8040,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"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\"},\n \"routing\": {\n \"type\": \"single\",\n \"data\": \"stripe\"\n }\n}", + "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": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "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
ci
Fix Stripe collection to address check failure (#2078)
66978593f8dc553916c821510e66c73dbee5c1e1
2023-06-17 00:06:45
Gnanasundari24
ci(postman-collection-runner): add `workflow_dispatch` trigger and fix failing CI runs (#1461)
false
diff --git a/.github/workflows/postman-collection-runner.yml b/.github/workflows/postman-collection-runner.yml index c963e064449..98b4d92517d 100644 --- a/.github/workflows/postman-collection-runner.yml +++ b/.github/workflows/postman-collection-runner.yml @@ -4,6 +4,7 @@ on: schedule: # Run workflow at 6 AM and 6 PM IST - cron: "30 0,12 * * *" + workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -33,6 +34,8 @@ jobs: runs-on: ubuntu-latest needs: api_tests steps: + - name: Checkout repository + uses: actions/checkout@v3 - name: Run Newman run: newman run postman/hyperswitch.postman_collection.json --env-var admin_api_key=${{ secrets.INTEG_ADMIN_API_KEY }} --env-var baseUrl=${{ secrets.INTEG_BASE_URL }} --env-var connector_api_key=${{ secrets.STRIPE_API_KEY }}
ci
add `workflow_dispatch` trigger and fix failing CI runs (#1461)
59a2bc434dca0d9faeceaa42b965f4ba4e93b1a9
2024-03-14 12:54:28
DEEPANSHU BANSAL
chore(config): [AUTHORIZEDOTNET] Add apple pay manual flow to dashboard (#4080)
false
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"
chore
[AUTHORIZEDOTNET] Add apple pay manual flow to dashboard (#4080)
6f1a1a3bcb7466738b018a773a5fe4adc5cf2887
2023-05-31 20:25:25
Kushneryk Pavel
feat(db): implement `EventInterface` for `MockDb` (#1289)
false
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index b60eb29e6af..9023cf71d07 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -117,6 +117,7 @@ pub struct MockDb { redis: Arc<redis_interface::RedisConnectionPool>, api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, cards_info: Arc<Mutex<Vec<storage::CardInfo>>>, + events: Arc<Mutex<Vec<storage::Event>>>, } impl MockDb { @@ -134,6 +135,7 @@ impl MockDb { redis: Arc::new(crate::connection::redis_connection(redis).await), api_keys: Default::default(), cards_info: Default::default(), + events: Default::default(), } } } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index aed2f285bfb..8148f2a8a8b 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -46,16 +46,94 @@ impl EventInterface for Store { impl EventInterface for MockDb { async fn insert_event( &self, - _event: storage::EventNew, + event: storage::EventNew, ) -> CustomResult<storage::Event, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_events = self.events.lock().await; + let now = common_utils::date_time::now(); + + let stored_event = storage::Event { + #[allow(clippy::as_conversions)] + id: locked_events.len() as i32, + event_id: event.event_id, + event_type: event.event_type, + event_class: event.event_class, + is_webhook_notified: event.is_webhook_notified, + intent_reference_id: event.intent_reference_id, + primary_object_id: event.primary_object_id, + primary_object_type: event.primary_object_type, + created_at: now, + }; + + locked_events.push(stored_event.clone()); + + Ok(stored_event) } async fn update_event( &self, - _event_id: String, - _event: storage::EventUpdate, + event_id: String, + event: storage::EventUpdate, ) -> CustomResult<storage::Event, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let mut locked_events = self.events.lock().await; + let mut event_to_update = locked_events + .iter_mut() + .find(|e| e.event_id == event_id) + .ok_or(errors::StorageError::MockDbError)?; + + match event { + storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified, + } => { + if let Some(is_webhook_notified) = is_webhook_notified { + event_to_update.is_webhook_notified = is_webhook_notified; + } + } + } + + Ok(event_to_update.clone()) + } +} + +#[cfg(test)] +mod tests { + use storage_models::enums; + + use crate::{ + db::{events::EventInterface, MockDb}, + types::storage, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_mockdb_event_interface() { + let mockdb = MockDb::new(&Default::default()).await; + + let event1 = mockdb + .insert_event(storage::EventNew { + event_id: "test_event_id".into(), + event_type: enums::EventType::PaymentSucceeded, + event_class: enums::EventClass::Payments, + is_webhook_notified: false, + intent_reference_id: Some("test".into()), + primary_object_id: "primary_object_tet".into(), + primary_object_type: enums::EventObjectType::PaymentDetails, + }) + .await + .unwrap(); + + assert_eq!(event1.id, 0); + + let updated_event = mockdb + .update_event( + "test_event_id".into(), + storage::EventUpdate::UpdateWebhookNotified { + is_webhook_notified: Some(true), + }, + ) + .await + .unwrap(); + + assert!(updated_event.is_webhook_notified); + assert_eq!(updated_event.primary_object_id, "primary_object_tet"); + assert_eq!(updated_event.id, 0); } }
feat
implement `EventInterface` for `MockDb` (#1289)